我想在运行时将数字转换为2位小数(总是显示两位小数)。我尝试了一些代码,但它只是如此,如下所示
20.03034 >> 20.03
20.3 >> 20.3 ( my code only rounds not converts )
然而,我希望它能做到这一点:
20.03034 >> 20.03
20.3 >> 20.30 (convert it to two decimal places)
我的代码如下:
angle = a variable
angle_screen = a variable
DecimalFormat df = new DecimalFormat("#.##");
angle = Double.valueOf(df.format(angle));
angle_screen.setText(String.valueOf(angle) + tmp);
任何有关如何做到这一点的帮助都会很棒,谢谢。
答案 0 :(得分:65)
试试这个new DecimalFormat("#.00");
<强>更新强>:
double angle = 20.3034;
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(angle);
System.out.println(angleFormated); //output 20.30
您的代码未正确使用小数格式
模式中的0表示必填数字,#表示可选数字。
更新2 :检查下面的回答
如果您希望0.2677
格式为0.27
,则应使用new DecimalFormat("0.00");
,否则将.27
答案 1 :(得分:21)
DecimalFormat df=new DecimalFormat("0.00");
使用此代码可获得精确的两位小数。 即使值为0.0,也会给出0.00作为输出。
相反,如果您使用:
DecimalFormat df=new DecimalFormat("#.00");
它不会将 0.2659 转换为 0.27 。您将得到 .27 等答案。
答案 2 :(得分:15)
试试这个:String.format("%.2f", angle);
答案 3 :(得分:2)
尝试
DecimalFormat df = new DecimalFormat("#,##0.00");