Java中的toPrecision()是否有等价物?

Eri*_*ler 4 java

在将算法从JavaScript移植到Java时,我遇到了需要替换JavaScript的toPrecision()的问题.问题是我不知道数字的大小有多大,所以我不能使用格式正确的NumberFormat.

是否有提供类似功能的标准类?

编辑这是我想出的:

   double toPrecision(double n, double p) {
        if (n==0) return 0;

        double e = Math.floor(Math.log10(Math.abs(n)));
        double f = Math.exp((e-p+1)*Math.log(10));

        return Math.round(n/f)*f;
    }
Run Code Online (Sandbox Code Playgroud)

原则上,它做了正确的事情,但舍入错误完全毁了它.例如, toPrecision(12.34567, 3)退货12.299999999999997

编辑2此版本适用于12个测试用例中的11个...

   double toPrecision(double n, double p) {
        if (n==0) return 0;

        double e = Math.floor(Math.log10(Math.abs(n)));
        double f = Math.round(Math.exp((Math.abs(e-p+1))*Math.log(10)));
        if (e-p+1<0) {
            f = 1/f;
        }

        return Math.round(n/f)*f;
    }
Run Code Online (Sandbox Code Playgroud)

toPrecision(0.00001234567, 3)仍然返回1.2299999999999999E-5而不是1.23E-5

Jig*_*shi 12

使用BigDecimalsetScale()方法来设置精度

BigDecimal bd = new BigDecimal("1.23456789");
System.out.println(bd.setScale(3,BigDecimal.ROUND_HALF_UP));
Run Code Online (Sandbox Code Playgroud)

产量

1.235
Run Code Online (Sandbox Code Playgroud)

看到

  • 这并未显示三位有效数字,例如"12345678.9并应返回12300000" (2认同)