I want to round a Java BigDecimal to a certain number of significant digits (NOT decimal places), e.g. to 4 digits:
12.3456 => 12.35 123.456 => 123.5 123456 => 123500
etc. The basic problem is how to find the order of magnitude of the BigDecimal, so I can then decide how many place to use after the decimal point.
All I can think of is some horrible loop, dividing by 10 until the result is <1, I am hoping there is a better way.
BTW, the number might be very big (or very small) so I can’t convert it to double to use Log on it.
The easierst solution is:
No String conversion is necessary, it is based purely on
BigDecimalarithmetic and therefore as efficient as possible, you can choose theRoundingModeand it is small. If the output should be aString, simply append.toPlainString().