1

I get number representing strings like

248.03500000066338
313.44999999979470
4.2346999999

and I need to round them to something like

248.035
313.45
4.2347

while keeping a fixed relative precision of let's say 6 significant figures. I could do it using Math.log10, computing what absolute precision is needed, and rounding correspondingly, but I wonder if there's a simple way.


Ideally, the resulting number should be such that it does not produce the trailing nines when converted to string, but this is not needed and maybe impossible.

maaartinus
  • 44,714
  • 32
  • 161
  • 320

1 Answers1

2

It might not be the most performant solution but I think this is the easiest one:

BigDecimal input = new BigDecimal("248.03500000066338");
double rounded = input.round(new MathContext(6)).doubleValue();
jakub.petr
  • 2,951
  • 2
  • 23
  • 34