5

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?

Saobi
  • 16,121
  • 29
  • 71
  • 81
  • possible duplicate of [Why does Java BigDecimal return 1E+1?](http://stackoverflow.com/questions/925232/why-does-java-bigdecimal-return-1e1) – polygenelubricants Jul 20 '10 at 16:03

4 Answers4

3

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.

Troy Alford
  • 26,660
  • 10
  • 64
  • 82
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
2

I think that BigDecimal.toPlainString() is the method you need. However, note that the division itself will throw an exception when the decimal representation is infinite, such as with 1/3.

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
  • Can you give an example of where `toString()` doesn't throw an exception and `toPlainString()` does? – polygenelubricants Jul 20 '10 at 15:52
  • 2
    @polygenelubricants: It was my mistake, I fixed the response. The ArithmeticException occurs when dividing. A BigDecimal can not handle infinite decimal representation. – Eyal Schneider Jul 20 '10 at 16:15
  • 1
    yes, I asked that question on stackoverflow =) http://stackoverflow.com/questions/2749375/arithmeticexception-thrown-during-bigdecimal-divide – polygenelubricants Jul 20 '10 at 16:28
1

BigDecimal.toString or toPlainString would help.

Jackie
  • 25,199
  • 6
  • 33
  • 24
0

You can use BigDecimal.toPlainString() to return "a string representation of this BigDecimal without an exponent field".

The scientific notation on the other hand is returned by BigDecimal.toEngineeringString().

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623