Search code examples
javabigdecimal

Setting scale to a negative number with BigDecimal


Does it ever make sense to set the scale to a negative number like this?

BigDecimal result;
    .
    .
    .
result = result.setScale(-1, RoundingMode.HALF_UP)

What happens if you do?


Solution

  • Yes, it makes sense to set the scale to a negative number in certain situations. That just means that the number is rounded to the nearest 10 to the -scale number, or just 10 in this case.

    BigDecimal bd = new BigDecimal(1094);
    bd = bd.setScale(-1, RoundingMode.HALF_UP);
    System.out.println(bd);
    System.out.println(bd.doubleValue());
    

    Prints

    1.09E+3
    1090.0
    

    The 1.09E+3 is equivalent to the double value 1090.0.

    This is useful when the scientific measurement for a quantity has less significant digits than the total number of digits necessary to represent the number normally. The precision of such a number is less than the size of the number.

    If Earth's distance from the Sun is given as 92,960,000 miles, and if this value is only 5 significant digits, then that is equivalent to

    BigDecimal bd = new BigDecimal(92960000.0);
    bd = bd.setScale(-3, RoundingMode.HALF_UP);// 3 insignificant/imprecise "0" digits
    System.out.println(bd);
    

    Which prints

    9.2960E+7
    

    The number is rounded to the nearest 1,000.