1

I want to do some simple math with some very small and very large numbers. I figured I'd start with BigDecimal:

scala> java.math.BigDecimal.valueOf(54, 45) 
res0: java.math.BigDecimal = 5.4E-44

How do I then get the the mantissa? Either 54 or 5.4 would be fine.

pr1001
  • 21,727
  • 17
  • 79
  • 125
  • Can you not div the number by 10 in a loop? – SOUser Mar 11 '11 at 20:17
  • What should the "mantissa" be for 10 scaled by 3, versus 1 scaled by 2? Both represent 0.1, but `BigDecimal#unscaledValue()` returns a different result for instances constructed via `BigDecimal.valueOf(10, 3)` and `BigDecimal.valueOf(1, 2)`. – seh Mar 11 '11 at 23:10

1 Answers1

2

BigDecimal.unscaledValue():

BigDecimal bd = BigDecimal.valueOf(54, 45);
System.out.println(bd.unscaledValue()); //prints "54"

The result of this method is a BigInteger since BigDecimal has arbitrary length decimal precision.

Edit

Here's the cleanest way I found to get the other way (5.4):

  bd.scaleByPowerOfTen(bd.scale() + 1 - bd.precision());

This I've tested less but it should cover all cases. It scales the number such that there is no decimal fraction (bd.scale()), but then scales back so that only one number is left of the decimal point (1 - bd.precision()).

Mark Peters
  • 80,126
  • 17
  • 159
  • 190