Question about double | Sololearn: Learn to code for FREE!


Question about double

public class Program { public static void main(String[] args) { double a = 12.3; double b = 12.0; double c = a-b; System.out.println(c); //output: 0.300000000000007 double d = Math.rint(c*10) / 10; System.out.println(d); //output: 0.3 } } Why I have to use Math.rint to get 0.3? Has it do to with the type double or with Java?

1/1/2019 11:21:07 PM

Denise Roßberg

5 Answers

New Answer


Decimal fractions can't be stored exactly on a binary computer. There is a precision error. For example, in some languages, if you tried this: x=1.0/3.0*3.0 you would get 0.999999999 instead of 1.0000000


I'm not good with Java, but in most languages it should be the same so, yes you should use some kind of rounding or printing mechanism. For example, in C: printf("%7.1f\n",1.0/3.0*3.0); should display 1.0


Not necessarily, usually double precision is used for large numbers only


Thank you for the fast answer. So I should every time use this math method when I use double?


But in my case I don't have large. The code above belongs to my program: It did'nt worked without using Math.rint ().