1

My problem while I am converting Double to BigDecimal I am loosing original value. My requirement like input would be like Double val = 10435383974769502920d and want to convert like 10435.383974769502920 but getting below output. I have tried with Double BigDecimal..but no success

Double val = 10435383974769502920d;
System.out.println(BigDecimal.valueOf(val).movePointLeft(15));

output : 10435.383974769502
satish
  • 21
  • 3
  • My problem is I am dealing with signals and watts so cant change value at any cost... – satish Jun 21 '18 at 23:05
  • Its not same as u suggested they ware using decimal value however I want to convert to decimal a non decimal value, while converting its limiting somehow till 18 digit only – satish Jun 21 '18 at 23:38

1 Answers1

2
Double val = 10435383974769502920d;

A double simply can't hold that many digits. Doubles are limited to ~15 decimal digits of precision. It's not BigDecimal that's losing the extra digits; it's the double you're starting with.

>>> System.out.printf("%f\n", 10435383974769502920d);
10435383974769502000.000000

Construct the BigDecimal with a string to avoid losing precision.

String val = "10435383974769502920";
System.out.println(new BigDecimal(val).movePointLeft(15));
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Good answer - want to add that you don’t need movePointLeft, you can just put the decimal point at the right place in the input string to BigDecimal – Erwin Bolwidt Jun 21 '18 at 23:26
  • Erwin I have tried to put . in String it self its working as well but in code review..I have to remove that – satish Jun 21 '18 at 23:55