我应该在该函数中更改什么才能获得类似 0.00 的效果?
为了获得最多两位小数的分数点值,我使用这个函数:
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("##.##");
return Double.valueOf(twoDForm.format(d));
但是,虽然有一个像“5.50”这样的值,但使用这个函数我只得到“5.5”。 相反,我想用上面的函数得到 5.50。那么我应该改变什么?
请给我更新的函数或任何更改输出(如“0.00”)的建议。
To get the fraction point value up to two decimal points, I use this function:
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("##.##");
return Double.valueOf(twoDForm.format(d));
But while there is a value like "5.50", then with this function I got only "5.5".
Instead of that, I want to get the 5.50 with the above function. So what should I have to change?
Please give me the updated function or any suggestions to change the output like "0.00".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的示例可以很好地将数字四舍五入到两位数。但是您将丢失尾随零,因为数字变量(双精度型、浮点型……)不存储任何格式信息。
如果你想看到尾随零(如 5.50),你必须格式化输出中的数字:
Your example works fine for rounding numbers to 2 digits. But you will lose trailing zeros, because numeric variables (double, float, ...) do not store any formating information.
If you want to see trailing zeros (like 5.50) you have to format the numbers on output:
使用格式:
当您使用
#
,零值显示为不存在。使用0
将确保显示数字或 0。Use the format:
When you use
#
, zero values display as absent. Using a0
will ensure that either a digit or a 0 is displayed.DecimalFormat.format 返回一个 String (不是 StringBuffer),然后您将获得 Double.valueOf(...)。然后返回双精度值,我假设当您打印它时使用它自己的 toString() 来显示。您需要对返回的双精度值运行 DecimalFormat.format。
DecimalFormat.format returns a String (not a StringBuffer), which you are then getting the Double.valueOf(...). You then return the double value, which I assume when you print it uses it's own toString() to be displayed. You need to run the DecimalFormat.format on the double value returned.