Math.round和功能的String.format不围捕正确所有浮点值[复制]

问题描述 投票:0回答:1

这个问题已经在这里有一个答案:

我试图Math.round和的String.format功能全面浮点/双精度值。

1)使用Math.round功能

Math.round(floatValue* 10.0) / 10.0;

对于的floatValue 40.55,结果是40.6 //正确和预期结果。

对于的floatValue 30.05,结果为30.0 //错误的结果。预期结果:30.1

2)使用的String.format功能

String.format("%.1f", floatValue);

对于的floatValue 40.55的结果是40.6 //正确和预期结果。

对于的floatValue 59.65的结果是59.6 //错误的结果。预期结果:59.7

为什么同样的功能是不同的浮点值的行为不同。

java android floating-point rounding
1个回答
0
投票

在可以与可视化

    float fv = 30.05f;
    System.out.println((fv));
    System.out.println((fv * 10.0));
    System.out.println(Math.round(fv * 10.0));
    System.out.println(Math.round(fv * 10.0) / 10.0);

结果

30.05
300.49999237060547
300
30.0

正如你可以看到30.05实际存储为30.49999237060547所以这就是为什么它似乎它舍去。见@EricPostpischi更简洁的解释中的注释。

https://rules.sonarsource.com/java/tag/misra/RSPEC-1244

What's wrong with using == to compare floats in Java?

© www.soinside.com 2019 - 2024. All rights reserved.