【问题标题】:Convert a number to 2 decimal places in Java在 Java 中将数字转换为小数点后 2 位
【发布时间】:2012-02-05 11:17:49
【问题描述】:

我想在运行时将一个数字转换为 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);

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

【问题讨论】:

  • 您的代码存在某种缺陷。您将双精度转换为具有特殊格式的字符串。然后将其转换回双精度,然后将其转换回字符串而不指定任何格式。我想那是错误的。 tmp 变量的用途也不明显。
  • 你应该阅读DecimalFormat API - 答案就在那里,而且很清楚。

标签: java decimal


【解决方案1】:

试试这个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

【讨论】:

  • @Necroqubus 您将 java.text.DecimalFormat (API 1) 与 android.icu.text.DecimalFormat (API 24) 混淆了。请在到处发布错误信息之前进行适当的研究。
  • 请注意,DecimalFormat 不是线程安全的。
【解决方案2】:

试试

DecimalFormat df = new DecimalFormat("#,##0.00");

【讨论】:

    【解决方案3】:

    试试这个:String.format("%.2f", angle);

    【讨论】:

    • 最小 API 低于 24 的最佳答案!谢谢! :)
    【解决方案4】:
    DecimalFormat df=new DecimalFormat("0.00");
    

    使用此代码可获得精确的两位小数。 即使值为 0.0,它也会给 u 0.00 作为输出。

    如果你使用:

    DecimalFormat df=new DecimalFormat("#.00");  
    

    它不会将 0.2659 转换为 0.27。你会得到类似.27的答案。

    【讨论】:

    • 为什么这没有更多的选票?!这是应该添加到已接受答案中的重要信息
    • 为什么它没有将我的浮点值 98786545/10^6 转换为两位十进制格式。将其转换为两位小数后,我想将其保存为字符串。
    • @sports 需要 API 级别 24,因此对于具有兼容性的项目来说是非常糟糕的解决方案
    猜你喜欢
    • 2013-07-02
    • 2021-11-30
    • 1970-01-01
    • 2012-04-10
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多