java - 使用最多五位数字来格式化 double 值,必要时四舍五入小数位

标签 java number-formatting

我有double我想转换为 String 的值具有以下格式限制的值:

number_of_fraction_digits = max( 0, 5 - number_of_integer_digits )

本质上,我希望尽可能将位数保留为 5,必要时四舍五入小数位。例如:

 float          String
-------------------------
     1               1
   100             100
100000          100000
 99999           99999
 99999.99        99999
  9999.99         9999.9
   999.99          999.99
    23.34324        23.343

我研究过使用 DecimalFormat但据我所知,它并没有完全实现我所追求的目标。

它允许使用 setMaximumFractionDigits() 设置最大小数位数但据我所知,我必须计算整数位数并自己执行上述计算。

所以基本的问题是是否有一种漂亮、干净的内置方式以这种方式格式化数字。

最佳答案

public class SignificantFormat {

    public static String formatSignificant(double value, int significant)
    {
        MathContext mathContext = new MathContext(significant, RoundingMode.DOWN);
        BigDecimal bigDecimal = new BigDecimal(value, mathContext);
        return bigDecimal.toPlainString();
    }

    public static void main(String[] args) {
        double[] data = { 1, 100, 100000, 99999, 99999.99, 9999.99, 999.99, 23.34324 };
        for(double d: data){
            System.out.printf("Input: %10s \tOutput: %10s\n", Double.toString(d), formatSignificant(d, 5));
        }
    }
}

关于java - 使用最多五位数字来格式化 double 值,必要时四舍五入小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9978205/

相关文章:

java - 我的布局在低 dpi 设备上无法正确缩放

java - 无法保留堆空间

java - Jframe的背景颜色根本不会改变

php - 如何在数据库中正确插入浮点变量

JavaScript如何显示数字

Java 理解 Math.getExponent(Double)

html - 如何在html中写有理数

java - 是否可以在循环中使用单个语句反转链表?

php - 如何在没有千位分隔符和舍入函数的情况下使用 number_format

java - Selenium webdriver 显式等待警报抛出 UnhandledAlertException