gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:03:13 26 4
gpt4 key购买 nike

在将算法从 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;
}

原则上,它做了正确的事情,但舍入错误完全毁了它。例如,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;
}

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

最佳答案

使用BigDecimalsetScale()方法设置精度

BigDecimal bd = new BigDecimal("1.23456789");
System.out.println(bd.setScale(3,BigDecimal.ROUND_HALF_UP));

输出

1.235

关于java - Java 中是否有 toPrecision() 的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12054006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com