【问题标题】:Rounding double value into two significant digits in java [duplicate]在java中将双精度值舍入为两位有效数字[重复]
【发布时间】:2013-04-08 07:54:53
【问题描述】:

我想要一个函数,将双精度值四舍五入为两位有效数字 现在我正在使用以下功能

private static DecimalFormatSymbols DFS;
private static DecimalFormat myFormatter;
public static String DoubleToFormatedString(double value) {
    DFS = new DecimalFormatSymbols();
    DFS.setDecimalSeparator('.');
    myFormatter = new DecimalFormat("############.##");
    myFormatter.setDecimalFormatSymbols(DFS);
    return myFormatter.format(value);
}

但是有了这个函数,例如:我得到一个四舍五入的数字 2.6,我需要得到这个像 2.60。 '0' 应该出现在 1 个有效数字的右侧。应该做出什么改变?或任何其他方式请帮助我

【问题讨论】:

标签: java android rounding number-formatting


【解决方案1】:

如下替换您的格式化程序

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

更多细节可以参考这个SO问题:Format double to 2 decimal places with leading 0s

【讨论】:

    【解决方案2】:

    试试

    new DecimalFormat("#.00");
    

    【讨论】:

      【解决方案3】:

      是的,只需使用

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

      而不是

       DecimalFormat myFormatter = new DecimalFormat("############.##");
      

      【讨论】:

        猜你喜欢
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-27
        • 2011-08-08
        • 1970-01-01
        • 2021-07-13
        • 2011-01-22
        相关资源
        最近更新 更多