Search code examples
javascalebigdecimalscientific-notation

Transform a BigDecimal with a negative scale to a positive scale


I am getting BigDecimal values in the scientific notation, i.e., 1E+3 and has a scale of -3. How do I convert it to 1000 with scale 0? I see that you can use toPlainString() and then is there a direct way of achieving this?


Solution

  • If I understand you correctly, d = d.setScale(0) will work:

    BigDecimal d = BigDecimal.valueOf(1e3).setScale(-3);
    System.out.println(d.unscaledValue());
    d = d.setScale(0);
    System.out.println(d.unscaledValue());
    

    Output is:

    1
    1000
    

    Note that BigDecimal is immutable, thus you have to reassign it.