0
public class Test {
    public static void main(String[] args){
         System.out.println(new BigDecimal(58.34));
    }
}

If I run above given program in Java, it is giving me output like: 58.340000000000003410605131648480892181396484375

Why is it?

Sharp Edge
  • 4,144
  • 2
  • 27
  • 41
Vishal Zanzrukia
  • 4,902
  • 4
  • 38
  • 82

3 Answers3

4

You pass a double when you construct the BigDecimal so the precision is already lost. Easiest fix is probably something like

System.out.println(new BigDecimal("58.34"));

Output is

58.34
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

This will cause due to double value

 System.out.println(new BigDecimal(58.34));
                                    ^^^ 

To avoid this you can use String value

 System.out.println(new BigDecimal("58.34"));
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
2

I think the BigDecimal.java best explains this feature.

API say's

Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer.

Notes:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • Hi @Ankur. really very nice explained :) Thanks. when should be use `public BigDecimal(double val)` contractor? Any relevant example? – Vishal Zanzrukia Jan 21 '15 at 06:39
  • @VishalZanzrukia answer edited, basically should be used when you need the exact conversion of passed in double value, will recommend you to read the docs , i have provided you in the links – Ankur Singhal Jan 21 '15 at 06:45