[英]DecimalFormat not rounding to two decimal places correctly
In the program I am writing I have a percent change function. 在我写的程序中,我有一个百分比变化功能。 With the numbers I'm using, it is supposed to return .03, yet I just get 0. Using a calculator, the value not formatted would be 0.03303.
使用我正在使用的数字,应该返回.03,但我只是得到0。使用计算器,未格式化的值为0.03303。 I want the number to be truncated after the second decimal place, no rounding at all.
我希望数字在小数点后第二位后被截断,根本不舍入。
df = new DecimalFormat("###.##;-###.##");
df.setRoundingMode(RoundingMode.DOWN);
//later in code
return df.format(((price-base_price)/price)*100.00D);
Edit: all variable types are doubles. 编辑:所有变量类型均为双精度。 Base price is 756.60 and price is 756.85
基本价格为756.60,价格为756.85
Your assumption about the value calculated in ((price-base_price)/price)*100.00D
is incorrect (I think you've probably invoked integer math, try ((price-base_price)/(double)price)*100.00D
). 您对
((price-base_price)/price)*100.00D
计算的值的假设是不正确的(我认为您可能已经调用了整数数学,请尝试((price-base_price)/(double)price)*100.00D
)。 When I directly execute, 当我直接执行时
double value = 0.03303;
DecimalFormat df = new DecimalFormat("###.##;-###.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(value));
I get the (requested) output 我得到了(请求的)输出
0.03
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.