简体   繁体   中英

Properly scaling BigDecimal

I have a situation where I want to scale values but in certain situations I'm getting an exception that indicates that rounding is required.

Lets say I have the numbers -9.999999 and 9.999999

Lets also say that I only care about precision up to 4 points after the decimal place. How can I scale both of these numbers properly without checking if the value is positive or negative?

If for example, I use RoundingMode.FLOOR , I get:

9.999999 scales to 99999
-9.999999 scales to -100000

What I would like is 9.9999 and -9.9999 , respectively.

Do I really need to check for the sign here? I feel like I'm missing something.

RoundingMode.DOWN always rounds toward zero, so that should be what you're looking for. That is, it will never increment your final digit when it rounds. It's equivalent to truncating your value at the specified scale.

BigDecimal bg1, bg2;

bg1 = new BigDecimal("123.12678");

// set scale of bg1 to 2 in bg2 using floor as rounding mode
    bg2 = bg1.setScale(2, RoundingMode.FLOOR);

String str = bg1 + " after changing the scale to 2 and rounding is
                 " +bg2;

// print bg2 value
    System.out.println( str );

Gives you output: 123.12678 after changing the scale to 2 and rounding is 123.12

Using RoundingMode.FLOOR RoundingMode.Floor acts as RoundingMode.DOWN for possitive numbers and as RoundingMode.UP for negative numbers

DecimalFormat decimalFormat = new DecimalFormat("00");
        decimalFormat.setRoundingMode(RoundingMode.FLOOR);
        System.out.println("FORMAT:" + decimalFormat.format(-94.5));<br>The result will be: FORMAT: - 95



RoundingMode.CEILING acts as RoundingMode.UP for possitive numbers and as RoundingMode.DOWN for negative

DecimalFormat decimalFormat = new DecimalFormat("00");
        decimalFormat.setRoundingMode(RoundingMode.CEILING);
        System.out.println("FORMAT:" + decimalFormat.format(-94.5));<br>The result will be:FORMAT: -94

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM