2

I am trying to get number of digits after decimal point in BigDecimal value.

BigDecimal big = new BigDecimal(1231235612.45);
    String[] str = big.toPlainString().split("\\.");

    System.out.println(" Decimal Value: " + str[1]);

Using this I am getting following output - Decimal Value: 4500000476837158203125. Actualy I want to display only 45 as per the original BigDecimal value (1231235612.45). So, my expected output is Decimal Value: 45. But, while conversion it adds more digits after decimal points. Is there any method or code to get exact same value from BigDecimal?

Nilesh
  • 133
  • 3
  • 10

1 Answers1

2

Don't use the double Constructor of BigDecimal (See Javadoc, it is discouraged).

use String constructor

new BigDecimal("1231235612.45");

or use MathContext

new BigDecimal(1231235612.45, MathContext.DECIMAL64);
OH GOD SPIDERS
  • 3,091
  • 2
  • 13
  • 16
  • 2
    @Nilesh The reason to not use the double constructor is that 1231235612.45 gets put into a 64-bit double, which cannot exactly represent it in a finite number of bits, The number 1231235612.4500000476837158203125 is the closest it can get. Changing the value by one bit produces a number less than 1231235612.45, but not quite as close as the one shown. – FredK Apr 26 '16 at 14:51