Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always display a BigDecimal object in full decimal format instead of scientific notation?

I have a BigDecimal object, myNumber, with unknown length. For example: 12345678.

I always want to divide this number by 1 million, so I do:

myNumber.divide(BigDecimal.valueOf(1000000))

I get 12.345678.

I want to display this as a string "12.345678", without cutting off ANY decimal places.

So I do

myNumber.divide(BigDecimal.valueOf(1000000)).toString()

This works fine with the above example. But if myNumber is something ridiculously small or big, such as:

0.00000001

After dividing 0.00000001 by a million and converting to string, it displays as scientific notation, which is not what I want. I want it to always display in full decimal format (in this case, 0.00000000000001).

Any ideas?

like image 633
Saobi Avatar asked Jul 20 '10 15:07

Saobi


1 Answers

You have to perform the division using the variant of divide() that includes a rounding mode and a scale, and set the scale large enough to include all the fractional digits.

int s = myNumber.scale();
BigDecimal result = myNumber.divide(BigDecimal.valueOf(1000000), s+6, RoundingMode.UNNECESSARY);

Then use toPlainString() to format.

like image 55
Jim Garrison Avatar answered Nov 06 '22 17:11

Jim Garrison