2

I am trying to apply formatting (, after 3 digits and rounding after 4 digits), using below code -

double a = 1231254125412512.231515235346;
NumberFormat formatter = new DecimalFormat("#,###");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits(4);
formatter.setMaximumFractionDigits(4);
System.out.println("Number : " + formatter.format(a));

Above code is working properly for the number -54125412512.231515235346 (result was -54,125,412,512.2315).

But it is not working for the number -1231254125412512.231515235346 (result -1,231,254,125,412,512.2000).

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79

2 Answers2

2

Double has a precision of 53 bit which is about 16 digits.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
1

Problem is you use double variable, and and hit max precision Double.MIN_VALUE.

SOURCE:

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (15 to 17 decimal digits, about 16 on average). 11 bits are used for the exponent and 1 bit is the sign bit.

To avoid this problem use BigDecimal instead:

BigDecimal a = new BigDecimal("-54125412512.231515235346");
BigDecimal b = new BigDecimal("-1231254125412512.231515235346");

NumberFormat formatter = new DecimalFormat("#,###");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits(4);
formatter.setMaximumFractionDigits(4);
System.out.println("Number : " + formatter.format(a));
System.out.println("Number : " + formatter.format(b));

OUTPUT:

Number : -54.125.412.512,2315
Number : -1.231.254.125.412.512,2315
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • 1
    Your solution is correct, but your first statement is not. 1231254125412512.231515235346 < Double.MAX_VALUE and (-1231254125412512.231515235346) > Double.MIN_VALUE. The problems is that a double doesn't have the precision to hold a number that is so large and has so much precision so it will be rounded. – Erwin Bolwidt Jun 28 '16 at 08:36
  • @ErwinBolwidt corrected and linked a source. thanks a lot! – Jordi Castilla Jun 28 '16 at 08:40