简体   繁体   中英

Rounding issue in openjdk8

I'm seeing something strange issue while using the NumberFormat.format(double) in open jdk1.8. I know there was an issue with rounding in the prior versions that was fixed in this version, but still something seems off.

public static void main (String args[]) {
    double num = 16.34625;

    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMinimumFractionDigits(2); 
    nf.setMaximumFractionDigits(4);

            System.out.println("nf : " + nf.getRoundingMode());
            System.out.println("BigDecimal is " + new  BigDecimal(num).toString());     

    System.out.println("num after number format : " + nf.format(num));
}

Here's the actual result displayed:

nf : HALF_EVEN
num : 16.34625
BigDecimal is 16.346250000000001278976924368180334568023681640625
num after number format : 16.3463

But, I would have expected it to be rounded to 16.3462, since in HALF_EVEN mode, the digit to the left of the discarded number is even, so it should act as HALF_DOWN.

Here's the java doc to back this up ( https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html#HALF_EVEN ).

You can try to round off in the BigInteger itself. You can use the setScale method of that class.

System.out.println(new BigDecimal(num).setScale(4,BigDecimal.ROUND_HALF_EVEN));
//16.3463

You are right about everything. The only issue is, that your BigDecimal is not 16.34625, it's 16.346250000000001278976924368180334568023681640625. So the neighbours are not equidistant.

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