Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how to achieve this type of number rounding?

I am writing a small physics app. What I am planning to do is to make number rounding. The issue is that it is not a fixed rounding, but rather a variable rounding that depends on the value of the decimal digits. I will give an explanation for the issue.

  • I always need to keep the whole integer part (if any) and the first five decimal digits (if any).
  • half up rounding is always used.

    21.1521421056 becomes 21.15214
    34.1521451056 becomes 34.15215

  • If the result consists of only decimal digits then:

    • If the first five digits include non zero digits then keep them.

      0.52131125 becomes 0.52131
      0.21546874 becomes 0.21547
      0.00120012 becomes 0.0012

    • If the first five digits are all zero digits 0.00000 then go down to first five digits that include non zero digits.

      0.0000051234 becomes 0.0000051234
      0.000000000000120006130031 becomes 0.00000000000012001

I need to play this rounding while working with BigDecimal because it is a requirement for my needs.

like image 223
Saleh Feek Avatar asked Nov 01 '22 23:11

Saleh Feek


1 Answers

I think this will work, based on experimentation, if I understand correctly what you want. If d is a BigDecimal that contains the number:

BigDecimal rounded = d.round(new MathContext
    (d.scale() - d.precision() < 5 
        ? d.precision() - d.scale() + 5 
        : 5));
like image 193
ajb Avatar answered Nov 09 '22 10:11

ajb