在Java中,如何删除float中的所有0?
我想这样改变浮动:
10.5000 -> 10.5 10.0000 -> 10.0000 -> 10
如何删除小数点后的所有零,并将其更改为 float(如果有非零)或 int(如果只有零)?
提前致谢。
I'd like to change float like this way:
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)?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
为什么不尝试正则表达式呢?
Why not try regexp?
诀窍是浮点数和双精度数本身实际上并没有尾随零;这只是它们的打印方式(或初始化为文字)可能会显示它们。考虑这些示例:
您可以使用
DecimalFormat
修复“10.0”的示例: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:
You can use a
DecimalFormat
to fix the example of "10.0":java.math.BigDecimal 有一个 stripTrailingZeros() 方法,它将实现您正在寻找的内容。
java.math.BigDecimal has a stripTrailingZeros() method, which will achieve what you're looking for.
这使用两种不同的格式化程序来处理它:
This handles it with two different formatters:
您只需要使用如下格式类:
You just need to use format class like following:
根据需要格式化输出的数字。您无法删除内部“0”值。
Format your numbers for your output as required. You cannot delete the internal "0" values.
尝试使用 System.out.format
这是一个允许 c 样式格式的链接
http://docs.oracle.com/javase/tutorial/java/data /numberformat.html
Try using System.out.format
Heres a link which allows c style formatting
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
我遇到了同样的问题,并在以下链接中找到了解决方法:
StackOverFlow - 如何良好地格式化浮点数字符串没有不必要的小数 0
JasonD 的答案是我遵循的答案。它不依赖于区域设置,这对我的问题有好处,并且对于长值没有任何问题。
希望这有帮助。
从上面的链接添加内容:
产生:
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
The answer from JasonD was the one I followed. 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:
Produces: