简体   繁体   English

在Java中,如何删除浮点数中的所有0?

[英]in Java, how to delete all 0s in float?

I'd like to change float like this way:我想像这样改变浮动:

10.5000 -> 10.5 10.0000 -> 10 10.5000 -> 10.5 10.0000 -> 10

How can I delete all zeros after the decimal point, and change it either float (if there's non-zeros) or int (if there were only zeros)?如何删除小数点后的所有零,并将其更改为 float(如果有非零)或 int(如果只有零)?

Thanks in advance.提前致谢。

Well the trick is that floats and doubles themselves don't really have trailing zeros per se;诀窍是浮点数和双精度数本身并没有真正的尾随零; it's just the way they are printed (or initialized as literals) that might show them.这只是可能显示它们的打印方式(或初始化为文字)。 Consider these examples:考虑以下示例:

Float.toString(10.5000); // => "10.5"
Float.toString(10.0000); // => "10.0"

You can use a DecimalFormat to fix the example of "10.0":您可以使用DecimalFormat来修复“10.0”的示例:

new java.text.DecimalFormat("#").format(10.0); // => "10"

为什么不试试正则表达式?

new Float(10.25000f).toString().replaceAll("\\.?0*$", "")

您只需要使用如下格式类:

new java.text.DecimalFormat("#.#").format(10.50000);

This handles it with two different formatters:这使用两种不同的格式化程序来处理它:

double d = 10.5F;
DecimalFormat formatter = new DecimalFormat("0");
DecimalFormat decimalFormatter = new DecimalFormat("0.0");
String s;
if (d % 1L > 0L) s = decimalFormatter.format(d);
else s = formatter.format(d);

System.out.println("s: " + s);

java.math.BigDecimal has a stripTrailingZeros() method, which will achieve what you're looking for. java.math.BigDecimal 有一个 stripTrailingZeros() 方法,它可以实现你想要的。

BigDecimal myDecimal = new BigDecimal(myValue);
myDecimal.stripTrailingZeros();
myValue = myDecimal.floatValue();

Format your numbers for your output as required.根据需要格式化输出的数字。 You cannot delete the internal "0" values.您不能删除内部“0”值。

I had the same issue and find a workaround in the following link: StackOverFlow - How to nicely format floating numbers to string without unnecessary decimal 0我遇到了同样的问题,并在以下链接中找到了解决方法: StackOverFlow - 如何在没有不必要的十进制 0 的情况下很好地将浮点数格式化为字符串

The answer from JasonD was the one I followed. JasonD 的回答是我所关注的。 It's not locale-dependent which was good for my issue and didn't have any problem with long values.它不依赖于语言环境,这对我的问题有好处,并且对长值没有任何问题。

Hope this help.希望这有帮助。

ADDING CONTENT FROM LINK ABOVE:从上面的链接添加内容:

public static String fmt(double d) {
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
    }

Produces:产生:

232
0.18
1237875192
4.58
0
1.2345

Try using System.out.format尝试使用 System.out.format

Heres a link which allows c style formatting http://docs.oracle.com/javase/tutorial/java/data/numberformat.html这是一个允许 c 样式格式化的链接http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

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

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