Java中的toPrecision()是否有等价物? [英] Is there an equivalent for toPrecision() in Java?
问题描述
在将算法从JavaScript移植到Java时,我遇到了需要替换JavaScript的toPrecision()的问题。问题是我不知道数字的大小有多大,所以我不能使用格式正确的NumberFormat。
In porting an algorithm from JavaScript to Java, I've run into the problem that I need a replacement for JavaScript's toPrecision(). The problem is that I don't have a clue how small or large the numbers will be, so I can't use a simple NumberFormat with the right format.
是有一个标准类提供类似的功能吗?
Is there a standard class that offers a similar functionality?
编辑
这是我想出的:
EDIT Here is what I came up with:
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
In principle, it does the right thing, but rounding errors completely ruin it. For example,
toPrecision(12.34567, 3)
returns 12.299999999999997
编辑2
此版本适用于12个测试用例中的11个......
EDIT 2 This version works perfectly for 11 out of 12 test cases...
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
推荐答案
使用 BigDecimal
和 setScale()
方法设置精度
Use BigDecimal
and setScale()
method to set the precision
BigDecimal bd = new BigDecimal("1.23456789");
System.out.println(bd.setScale(3,BigDecimal.ROUND_HALF_UP));
输出
1.235
参见
- IDEone demo
这篇关于Java中的toPrecision()是否有等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!