0

I have a double value, for example:

double a = 12.1212123456543234;

I need to check the number of the digits after point and drop all digits from sixteenth. Here is my code to get digits after point:

String [] splitter  = String.valueOf(a).split("\\.");

But even if the number of the digits after the point is bigger then 15, I always get 15 digits, and last digit (fifteenth) replaced by the wrong. please help me.

Ali Azim
  • 160
  • 1
  • 15
anna
  • 433
  • 7
  • 18

1 Answers1

2

Double is a 64-bit floating point number. And its precision is limited to 15-16 digits after the point, that's why you get incorrect results.

If want to work with that large numbers you probably need BigDecimal.

BigDecimal decimal = new BigDecimal("12.1212123456543234");

If you want to round the decimal up to N digits, you can do it this way:

BigDecimal decimal = new BigDecimal("12.1212123456543234");
decimal = decimal.setScale(15, RoundingMode.CEILING);

You should also have a look at RoundingModes to select the rounding you need.

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28