Java - 格式化数字以仅打印小数部分
Java中有没有一种简单的方法来格式化小数、浮点数、双精度数等以仅打印数字的小数部分?我不需要整数部分,即使/特别是如果它为零! 我目前正在使用 String.indexOf(".") 方法与 String.substring() 方法相结合来选取小数点右侧的数字部分。有没有更干净的方法来做到这一点?在 DecimalFormat 类或 printf 方法中找不到任何内容。两者都始终在小数点前返回零。
Is there a simple way in Java to format a decimal, float, double, etc to ONLY print the decimal portion of the number? I do not need the integer portion, even/especially if it is zero!
I am currently using the String.indexOf(".") method combined with the String.substring() method to pick off the portion of the number on the right side of the decimal. Is there a cleaner way to do this? Couldn't find anything in the DecimalFormat class or the printf method. Both always return a zero before the decimal place.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过将 double 转换为 long 来删除该值的整数部分。然后,您可以从原始值中减去它,只留下小数值:
如果您想去掉前导零,您可以这样做:
You can remove the integer part of the value by casting the double to a long. You can then subtract this from the original value to be left with only the fractional value:
And if you want to get rid of the leading zero you can do this:
除以1并取余即可得到小数部分(使用“%”)。使用 DecimalFormat 格式化结果(使用“#”符号抑制前导 0):
这将打印 .22
Divide by 1 and get remainder to get decimal portion (using "%"). Use DecimalFormat to format result (using "#" symbol to suppress leading 0s):
this prints .22
这将打印 0.3
This will print 0.3