我应该在该函数中更改什么才能获得类似 0.00 的效果?

发布于 2024-12-09 04:28:53 字数 330 浏览 0 评论 0原文

为了获得最多两位小数的分数点值,我使用这个函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

太傻旳人生 2024-12-16 04:28:53

您的示例可以很好地将数字四舍五入到两位数。但是您将丢失尾随零,因为数字变量(双精度型、浮点型……)不存储任何格式信息。

如果你想看到尾随零(如 5.50),你必须格式化输出中的数字:

DecimalFormat twoDForm = new DecimalFormat("#0.00");         
System.out.println(twoDForm.format(d));

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:

DecimalFormat twoDForm = new DecimalFormat("#0.00");         
System.out.println(twoDForm.format(d));
静若繁花 2024-12-16 04:28:53

使用格式

new DecimalFormat("#0.00")

当您使用#,零值显示为不存在。使用 0 将确保显示数字或 0。

Use the format:

new DecimalFormat("#0.00")

When you use #, zero values display as absent. Using a 0 will ensure that either a digit or a 0 is displayed.

不打扰别人 2024-12-16 04:28:53

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文