我试图根据变量输入获得所需的输出。我可以接近我想要的东西,但似乎存在舍入数字的问题。
我想要的例子(输入>输出)。
30 > 30
30.0 > 30
30.5 > 30,5
30.5555 > 30,6
30.04 > 30
问题是最后一个回复为30.0。现在我明白为什么会发生这种情况(因为向上/向下舍入)
我的代码:
private String getDistanceString(double distance) {
distance = 30.55;
DecimalFormat df = new DecimalFormat(".#");
if (distance == Math.floor(distance)) {
//If value after the decimal point is 0 change the formatting
df = new DecimalFormat("#");
}
return (df.format(distance) + " km").replace(".", ",");
}
答案 0 :(得分:2)
将==
与浮点数一起使用几乎总是错误的。您应该使用Math.abs(a - b) < x
。
private String getDistanceString(double distance) {
DecimalFormat df = new DecimalFormat(".#");
if (Math.abs(distance - Math.round(distance)) < 0.1d) {
//If value after the decimal point is 0 change the formatting
df = new DecimalFormat("#");
}
return (df.format(distance) + " km").replace(".", ",");
}
public void test() {
double[] test = {30d, 30.0d, 30.5d, 30.5555d, 30.04d, 1d / 3d};
for (double d : test) {
System.out.println("getDistanceString(" + d + ") = " + getDistanceString(d));
}
}
答案 1 :(得分:0)
围绕它的黑客,是用正则表达式取代
return
(""+df.format(distance))
.replaceAll("\\.(0+$)?", ",") //replace . and trailing 0 with comma,
.replaceAll(",$","") //if comma is last char, delete it
+ " km"; //and km to the string