1

Can anyone explain the behaviour of double and float data types in following example. Why precision values are changing?

public class TestClass{
public static void main(String[] args) {

String st = "4.45";
double i = Double.parseDouble(st);
float fff = Float.parseFloat(st);

System.out.println("Float 4.45 outputs : *******************************");
System.out.println(fff);
int fpp = (int) (fff *100);
System.out.println(fff *100);
System.out.println(fpp);

System.out.println("Double 4.45 outputs : *******************************");
System.out.println(i);
int p = (int) (i *100);
System.out.println(i *100);
System.out.println(p);

String str = "9.45";
double ii = Double.parseDouble(str);
float ff = Float.parseFloat(str);

System.out.println("Float 9.45 outputs : *******************************");
System.out.println(ff);
int fp = (int) (ff *100);
System.out.println(ff *100);
System.out.println(fp);

System.out.println("Double 9.45 outputs : *******************************");
System.out.println(ii);
int pp = (int) (ii *100);
System.out.println(ii *100);
System.out.println(pp);


String strr = "9.40";
double iir = Double.parseDouble(strr);
float ffr = Float.parseFloat(strr);

System.out.println("Float 9.40 outputs : *******************************");
System.out.println(ffr);
int fpr = (int) (ffr *100);
System.out.println(ffr *100);
System.out.println(fpr);

System.out.println("Double 9.40 outputs : *******************************");
System.out.println(iir);
int ppr = (int) (iir *100);
System.out.println(iir *100);
System.out.println(ppr);
}
}

OUTPUT :

Float 4.45 outputs : *******************************

4.45

444.99997

444

Double 4.45 outputs : *******************************

4.45

445.0

445

Float 9.45 outputs : *******************************

9.45

945.0

945

Double 9.45 outputs : *******************************

9.45

944.9999999999999

944

Float 9.40 outputs : *******************************

9.4

939.99994

939

Double 9.40 outputs : *******************************

9.4

940.0

940

1 Answers1

1

Performing operations on Floats, Doubles and their primitive counterparts is prone to loss of precision in the decimals (e.g. the ii * 100 value you print).

This is why you typically use classes form the java.math package for, say, currency-related calculations (e.g. BigDecimal).

Mena
  • 47,782
  • 11
  • 87
  • 106
  • I know i can use Math.round() and other java.math package functions. But i want to know why "Performing operations on Floats, Doubles and their primitive counterparts is prone to loss of precision in the decimals" ? – Mananpreet Singh Jan 11 '16 at 12:50
  • You can find the relevant answers in the Java language specifications [here](http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.3). A maybe more user-friendly explanation can be found [here](http://floating-point-gui.de/languages/java/). – Mena Jan 11 '16 at 13:29