Transform a BigDecimal with a negative scale to a positive scale

1.2k views Asked by At

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?

1

There are 1 answers

0
Tagir Valeev On BEST ANSWER

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.