简体   繁体   中英

HALF_EVEN rounding doesn't work

I've read several articles about using decimal format and rounding and I think I am using it correctly, but somehow HALF_EVEN, HALF_DOWN or HALF_UP rounding doesn't work. Do you have any ideas if it has something to do with eclipse settings or do I really use the decimalformat incorrectly?

My goal is to round every number from .55 to .6 like in standard mathematical rounding. So...as I assumed...the best option is to round with "HALF_UP".

Code:

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Rounding {

    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat();
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(1);
        df.setRoundingMode(RoundingMode.HALF_UP);


        for (double x = 0.55; x < 10.0; x++) {
            System.out.println("Original value: " + x + "\tRounded value: " + df.format(x));
        }
    }
}

Result:

Original value: 0.55    Rounded value: 0,6
Original value: 1.55    Rounded value: 1,6
Original value: 2.55    Rounded value: 2,5
Original value: 3.55    Rounded value: 3,5
Original value: 4.55    Rounded value: 4,5
Original value: 5.55    Rounded value: 5,5
Original value: 6.55    Rounded value: 6,5
Original value: 7.55    Rounded value: 7,5
Original value: 8.55    Rounded value: 8,6
Original value: 9.55    Rounded value: 9,6

Once you have the numbers in double format you have already created hidden inaccuracy that can round numbers under or over the halfway mark without you seeing it.

You'll need to use BigDecimal.

To understand how this rounding works internally, add System.out.println("exact x: " + new BigDecimal(x)); inside the loop. It will print the exact value of x, compared to your current code, which only prints an approximate value.

When you understand what happens, fix your code by using integer arithmetic instead of floating point arithmetic wherever possible.

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