Wednesday, 18 May 2022

float vs double in Java

Java provide both float and double data types to represent real numbers. But you should know the key differences when you are working with float and double types in your application.

 

Following are the key differences between float and double.

 

a. double takes 8 bytes of storage, whereas float takes 4 bytes of storage.

 

b. You should use the suffix f or F to define a float variable.

float f1 = 1.23f;

float f2 = 1.23F;

 

c. A float variable can store a decimal value with 6-7 total digits of precision, where as a double variable can store a decimal value with 15-16 total digits of precision. You can confirm the same by running below program.

 

FloatAndDoubleDemo.java

package com.sample.app;

public class FloatAndDoubleDemo {
	
	public static void main(String[] args) {
		float f = 1.111111111111111111111111111111111111111111111f;
		double d = 1.111111111111111111111111111111111111111111111;
		
		System.out.println("f : "+ f);
		System.out.println("d : "+ d);
	}

}

 

Output

f : 1.1111112
d : 1.1111111111111112

 

From the output, you can confirm that the float is rounding off to 7 precision digits, whereas double is rounding off to 16 precision digits.

 

You may like

Interview Questions

How for-each or enhanced for loop works in Java?

How to solve UnsupportedClassVersionError in Java?

How to find the Java major and minor versions from a .class file

Can I run a class file that is compiled in lower environment?

How to solve the Error: Could not find or load main?

No comments:

Post a Comment