Java:d​​ouble:总是显示两位十进制数字 [英] Java: double: how to ALWAYS show two decimal digits

查看:115
本文介绍了Java:d​​ouble:总是显示两位十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用双重值,我想始终显示头两个十进制数字,即使它们是零。我使用这个函数舍入,如果我打印的值是3.47233322它(正确)打印3.47。但是当我打印时,例如打印的值为2.0。

  public static double round(double d){
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}

我要打印2.00!



有没有办法这样做,而不使用字符串?



谢谢!



编辑:从你的答案(我感谢你)我明白我没有告诉我正在搜索的内容(我很抱歉):我知道如何打印两位数后,使用您提出的解决方案...我想要的是直接存储在双值中的两位数字!所以当我做这样的事情 System.out.println(+ d)(其中d是我的double与值2)打印2.00。



我开始认为没有办法做到这一点...对吧?再次感谢你的回答,请让我知道如果你知道一个解决方案!

解决方案

你可以使用这样的东西:

  double d = 1.234567; 
DecimalFormat df = new DecimalFormat(#。00);
System.out.print(df.format(d));

编辑实际回答问题,因为我需要真正的答案,这是在谷歌和有人标记它作为答案,尽管事实上,当小数为0时,这不会起作用。


I use double values in my project and i would like to always show the first two decimal digits, even if them are zeros. I use this function for rounding and if the value I print is 3.47233322 it (correctly) prints 3.47. But when i print, for example, the value 2 it prints 2.0 .

public static double round(double d) {
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
}

I want to print 2.00!

Is there a way to do this without using Strings?

Thanks!

EDIT: from your answers (wich I thank you for) I understand that I wasn't clear in telling what I am searching (and I'm sorry for this): I know how to print two digits after the number using the solutions you proposed... what i want is to store in the double value directly the two digits! So that when I do something like this System.out.println("" + d) (where d is my double with value 2) it prints 2.00.

I'm starting to think that there is no way to do this... right? Thank you again anyway for your answers, please let me know if you know a solution!

解决方案

You can use something like this:

 double d = 1.234567;
 DecimalFormat df = new DecimalFormat("#.00");
 System.out.print(df.format(d));

Edited to actually answer the question because I needed the real answer and this came up on google and someone marked it as the answer despite the fact that this wasn't going to work when the decimals were 0.

这篇关于Java:d​​ouble:总是显示两位十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆