Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal format with DecimalFormat

I'm trying to get predictable behavior with rounding BigDecimal numbers to 15th digit. As a result I'm getting some either round up or round down.

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class NumberTest {
    public static void main(String[] args) {
        String pattern = "##############0.0##############";
        MathContext mc = new MathContext(15, RoundingMode.HALF_UP);
        NumberFormat numberFormat = new DecimalFormat(pattern);

        BigDecimal n1 = new BigDecimal(0.0452641706926935, mc);
        n1.setScale(15, BigDecimal.ROUND_HALF_UP);
        BigDecimal n2 = new BigDecimal(0.0123456789012345, mc);
        n2.setScale(15, BigDecimal.ROUND_HALF_UP);

        System.out.println("n1: "+n1+" ==> "+n1.doubleValue()+"="+numberFormat.format(n1.doubleValue()));
        System.out.println("n3: "+n2+" ==> "+n2.doubleValue()+"="+numberFormat.format(n2.doubleValue()));
    }
}

Output of my result:
n1: 0.0452641706926935 ==> 0.0452641706926935=0.045264170692694
n2: 0.0123456789012345 ==> 0.0123456789012345=0.012345678901234

n1 - rounded up n2 - rounded down

What am I missing?

thank you.

like image 699
dgene00 Avatar asked May 16 '26 04:05

dgene00


1 Answers

You're not actually using the BigDecimal for which you set the scale:

n2.setScale(15, BigDecimal.ROUND_HALF_UP);

This line should be:

n2 = n2.setScale(15, BigDecimal.ROUND_HALF_UP);

Change to that and it works as expected.

like image 121
user1676075 Avatar answered May 18 '26 15:05

user1676075



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!