Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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.

Try this:

   System.out.println(String.format("%.4f",lat));

where 4 in %.4f specified how many decimal places you want to display

Note that this will only format your output display. the actual value of lat however still 0.00770000000000000024702462297909733024425804615020751953125

You can also use NumberFormat and specify the fraction digits setMinimumFractionDigits(4)

BigDecimal lat =  new BigDecimal(0.0077);
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(4);
System.out.println(nf.format(lat));
 BigDecimal lat =  new BigDecimal(0.0077);
 lat=lat.setScale(4,RoundingMode.HALF_EVEN);
 System.out.println(lat);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top