Java 仅在需要时显示双精度小数(舍入问题)
我试图根据可变输入获得所需的输出。我可以接近我想要的,但似乎有一个四舍五入数字的问题 通过示例(输入>输出)了解我想要的内容 问题是最后一个返回为30.0。现在我明白了为什么会发生这种情况(因为四舍五入/四舍五入) 我的代码:Java 仅在需要时显示双精度小数(舍入问题),java,Java,我试图根据可变输入获得所需的输出。我可以接近我想要的,但似乎有一个四舍五入数字的问题 通过示例(输入>输出)了解我想要的内容 问题是最后一个返回为30.0。现在我明白了为什么会发生这种情况(因为四舍五入/四舍五入) 我的代码: private String getDistanceString(double distance) { distance = 30.55; DecimalFormat df = new DecimalFormat(".#");
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(".", ",");
}
对浮点数使用
=
几乎总是错误的。您应该使用Math.abs(a-b)
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));
}
}
私有字符串GetDistSectoring(双倍距离){
DecimalFormat df=新的DecimalFormat(“.#”);
if(数学绝对值(距离-数学圆(距离))<0.1d){
//如果小数点后的值为0,请更改格式
df=新的十进制格式(“#”);
}
返回(df.格式(距离)+“km”)。替换(“.”、“,”);
}
公开无效测试(){
双[]试验={30d,30.0d,30.5d,30.5555d,30.04d,1d/3d};
用于(双d:测试){
System.out.println(“GetDistSectoring(“+d+””)=“+GetDistSectoring(d));
}
}
围绕它的一个难题是用正则表达式替换它
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
无需替换即可获得逗号作为小数分隔符@LưuVĩnhPhúc谢谢您的添加。这看起来确实不错。谢谢你解决了我的问题,我真的为使用==感到羞耻。实际上,这不是进行浮点相等比较的好方法,我只是注意到,当它与我在问题中给出的示例一起工作时,如果输入是例如30.99,那么它不会做我想要的事情,这使得输出为31,0。应该是31。我试着对代码进行了一些调整,但得出的结论是,我对代码的理解不够,无法做到这一点。你能进一步帮助我吗?@RekijanKileren-尝试使用
Math.round
而不是Math.floor
。
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