我想在运行时将数字转换为2位小数(总是显示两位小数).我尝试了一些代码,但它只是如此,如下所示
20.03034 >> 20.03
20.3 >> 20.3 ( my code only rounds not converts )
Run Code Online (Sandbox Code Playgroud)
但是,我希望它能做到这一点:
20.03034 >> 20.03
20.3 >> 20.30 (convert it to two decimal places)
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
angle = a variable
angle_screen = a variable
DecimalFormat df = new DecimalFormat("#.##");
angle = Double.valueOf(df.format(angle));
angle_screen.setText(String.valueOf(angle) + tmp);
Run Code Online (Sandbox Code Playgroud)
任何有关如何做到这一点的帮助都会很棒,谢谢.
Rog*_*cia 70
试试这个 new DecimalFormat("#.00");
更新:
double angle = 20.3034;
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(angle);
System.out.println(angleFormated); //output 20.30
Run Code Online (Sandbox Code Playgroud)
您的代码未正确使用小数格式
模式中的0表示强制数字,#表示可选数字.
更新2:检查下面的答案
如果你想要0.2677格式化,0.27你应该使用new DecimalFormat("0.00");否则它将是.27
Ant*_*son 22
DecimalFormat df=new DecimalFormat("0.00");
Run Code Online (Sandbox Code Playgroud)
使用此代码可获得精确的两个小数点.即使该值为0.0,它也会给出0.00作为输出.
相反,如果您使用:
DecimalFormat df=new DecimalFormat("#.00");
Run Code Online (Sandbox Code Playgroud)
它不会将0.2659转换为0.27.你会得到像.27这样的答案.
| 归档时间: |
|
| 查看次数: |
138336 次 |
| 最近记录: |