正如其他人所指出的,正确的答案是使用DecimalFormat
或BigDecimal
。浮点数并没有十进制位,因此您根本无法首先将其舍入/截断为特定数量的十进制位。您必须以十进制基数工作,并且这就是这两个类所做的。
我发布以下代码作为对本主题中所有答案以及StackOverflow(以及其他地方)中建议先进行乘法,然后进行截断,最后进行除法的反例。支持这种技术的倡导者有责任解释为什么以下代码在超过92%的情况下会产生错误输出。
public class RoundingCounterExample
{
static float roundOff(float x, int position)
{
float a = x;
double temp = Math.pow(10.0, position);
a *= temp;
a = Math.round(a);
return (a / (float)temp);
}
public static void main(String[] args)
{
float a = roundOff(0.0009434f,3);
System.out.println("a="+a+" (a % .001)="+(a % 0.001));
int count = 0, errors = 0;
for (double x = 0.0; x < 1; x += 0.0001)
{
count++;
double d = x;
int scale = 2;
double factor = Math.pow(10, scale);
d = Math.round(d * factor) / factor;
if ((d % 0.01) != 0.0)
{
System.out.println(d + " " + (d % 0.01));
errors++;
}
}
System.out.println(count + " trials " + errors + " errors");
}
}
这个程序的输出:
10001 trials 9251 errors
编辑:为了回应下面的一些评论,我重新使用 BigDecimal
和 new MathContext(16)
来重做测试循环中的模数部分,代码如下:
public static void main(String[] args)
{
int count = 0, errors = 0;
int scale = 2;
double factor = Math.pow(10, scale);
MathContext mc = new MathContext(16, RoundingMode.DOWN);
for (double x = 0.0; x < 1; x += 0.0001)
{
count++;
double d = x;
d = Math.round(d * factor) / factor;
BigDecimal bd = new BigDecimal(d, mc);
bd = bd.remainder(new BigDecimal("0.01"), mc);
if (bd.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.ONE, mc).compareTo(BigDecimal.ZERO) != 0)
{
System.out.println(d + " " + bd);
errors++;
}
}
System.out.println(count + " trials " + errors + " errors");
}
结果:
10001 trials 4401 errors