Search code examples
javamathbigdecimalmantissa

Get the Mantissa of a Java BigDecimal


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.


Solution

  • 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()).