DecimalFormat 没有正确四舍五入到两位小数
DecimalFormat not rounding to two decimal places correctly
在我编写的程序中,我有一个百分比变化函数。对于我使用的数字,它应该是 return .03,但我只得到 0。使用计算器,未格式化的值将是 0.03303。我希望数字在小数点后第二位被截断,完全不四舍五入。
df = new DecimalFormat("###.##;-###.##");
df.setRoundingMode(RoundingMode.DOWN);
//later in code
return df.format(((price-base_price)/price)*100.00D);
编辑:所有变量类型都是双精度的。底价为 756.60,价格为 756.85
您对 ((price-base_price)/price)*100.00D
中计算的值的假设不正确(我认为您可能已经调用了整数数学,请尝试 ((price-base_price)/(double)price)*100.00D
)。当我直接执行时,
double value = 0.03303;
DecimalFormat df = new DecimalFormat("###.##;-###.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(value));
我得到(请求的)输出
0.03
在我编写的程序中,我有一个百分比变化函数。对于我使用的数字,它应该是 return .03,但我只得到 0。使用计算器,未格式化的值将是 0.03303。我希望数字在小数点后第二位被截断,完全不四舍五入。
df = new DecimalFormat("###.##;-###.##");
df.setRoundingMode(RoundingMode.DOWN);
//later in code
return df.format(((price-base_price)/price)*100.00D);
编辑:所有变量类型都是双精度的。底价为 756.60,价格为 756.85
您对 ((price-base_price)/price)*100.00D
中计算的值的假设不正确(我认为您可能已经调用了整数数学,请尝试 ((price-base_price)/(double)price)*100.00D
)。当我直接执行时,
double value = 0.03303;
DecimalFormat df = new DecimalFormat("###.##;-###.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(value));
我得到(请求的)输出
0.03