Try rounding the BigDecimal first, then calling its longValue() method:
The rounding takes the precision (number of digits) minus the number of decimals. This may go wrong if the rounding adds a digit (e.g. from 99.5 to 100), but initial tests show no problem.
I would prefer Till's solution. It handles cases like the jump form 99.xx to 100 better.
Joined: Jun 06, 2009
Rob Prime wrote:I would prefer Till's solution. It handles cases like the jump form 99.xx to 100 better.
I've chosen Till's solution because using this I create one object less (MathContext) but when I've changed rounding mode to HALF_UP in yours solution it worked pretty the same. (99.7 was converted to 100 properly). Perhaps I'm missing something.