在Java中将数字转换为2位小数 [英] Convert a number to 2 decimal places in Java

查看:4099
本文介绍了在Java中将数字转换为2位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时将数字转换为2位小数(总是显示两位小数)。我尝试了一些代码,但它只有,如下所示

I want to convert a number to a 2 decimal places (Always show two decimal places) in runtime. I tried some code but it only does, as shown below

 20.03034 >> 20.03
 20.3 >> 20.3  ( my code only rounds not converts )

但是,我希望它能做到这一点:

however, I want it to do this:

 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);

任何有关如何做到这一点的帮助都会很棒,谢谢。

Any help on how to do this would be great, thanks.

推荐答案

试试这个新的DecimalFormat(#。00);

更新

    double angle = 20.3034;

    DecimalFormat df = new DecimalFormat("#.00");
    String angleFormated = df.format(angle);
    System.out.println(angleFormated); //output 20.30

您的代码未正确使用小数格式

Your code wasn't using the decimalformat correctly

模式中的0表示必填数字,#表示可选数字。

The 0 in the pattern means an obligatory digit, the # means optional digit.

更新2 :检查下方回答

如果你想要 0.2677 格式为 0.27 你应该使用新的DecimalFormat(0.00); 否则它将是 .27

If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27

这篇关于在Java中将数字转换为2位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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