Why I get trailing so many numbers when I run below code?
BigDecimal lat = new BigDecimal(0.0077);
System.out.println(lat);
output >> 0.00770000000000000024702462297909733024425804615020751953125
I want to print exactly what I entered. How can I do this?
Most finite decimal fractions cannot be exactly represented by floating-point, so that is the approximation you get when you create the floating-point literal 0.0077.
To avoid the problem, use the constructor BigDecimal(String val) instead:
BigDecimal lat = new BigDecimal("0.0077");
As @TimB points out, if you already have a double value, you can also use:
BigDecimal lat = BigDecimal.valueOf(doubleVal);
Also, here is the mandatory reference to What Every Computer Scientist Should Know About Floating-Point Arithmetic.
When you have a number like 0.077 this cannot be exactly represented and in fact you get a number which is almost this, but with a small error. When you print this number as a string, the code to do this "knows" to discard the small error and you see the number you expect.
BigDecimal tries to give you a faithful representation and it is doing what it should even if this is surprising. What you want to use is the following method
BigDecimal bd = BigDecimal.valueOf(0.077);
In this case the BigDecimal takes the value as it would be printed, instead of the true value represented.
why is it so long?
To accurately represent a 53-bit fraction (double has a 53-bit mantissa) you need 53 decimal digits. e.g. every time you multiple by 10 to get another digit, you multiple 2 (and 5) which makes the lower bit 0 and eventually you guarentee to have all 0 bits and no more digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With