简体   繁体   English

HALF_EVEN舍入不起作用

[英]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. 我已经阅读了几篇关于使用十进制格式和舍入的文章,我认为我正确使用它,但不知何故HALF_EVEN,HALF_DOWN或HALF_UP舍入不起作用。 Do you have any ideas if it has something to do with eclipse settings or do I really use the decimalformat incorrectly? 如果它与eclipse设置有关或者我是否真的错误地使用了小数格式,你有什么想法吗?

My goal is to round every number from .55 to .6 like in standard mathematical rounding. 我的目标是将每个数字从.55到.6舍入,就像标准数学四舍五入一样。 So...as I assumed...the best option is to round with "HALF_UP". 所以...正如我所假设的......最好的选择是用“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. 一旦你有double格式的数字,你已经创建了隐藏的不准确性,可以将数字舍入到中途标记之下或之上,而不会看到它。

You'll need to use BigDecimal. 你需要使用BigDecimal。

To understand how this rounding works internally, add System.out.println("exact x: " + new BigDecimal(x)); 要了解此舍入如何在内部工作,请添加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. 与当前代码相比,它将打印x的确切值,该代码仅打印近似值。

When you understand what happens, fix your code by using integer arithmetic instead of floating point arithmetic wherever possible. 当您了解发生了什么时,请尽可能使用整数运算而不是浮点运算来修复代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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