我已经谷歌如何获得java中浮点数的2位小数。以下是我的代码。最后在这里float totalWeight = 0.1*levinWeight+0.8*lsmWeight;
我得到可能丢失精度的错误?我想首先将字符串转换为float,然后将其设置为2位小数。
float levinWeight = Float.parseFloat(dataOnlyCombine[2]);
float lsmWeight = Float.parseFloat(dataOnlyCombine[3]);
DecimalFormat df = new DecimalFormat("#.##");
levinWeight = Float.valueOf(df.format(levinWeight));
lsmWeight = Float.valueOf(df.format(lsmWeight));
float totalWeight = 0.1*levinWeight+0.8*lsmWeight;
答案 0 :(得分:4)
如果您担心精确度
float
,它具有任何可用选项的最低精度。我建议使用double
或BigDecimal
0.1 * x
会给您错误,因为0.1
无法准确表示。使用x / 10.0
的错误会更少。我会写这样的东西
double levinWeight = Double.parseDouble(dataOnlyCombine[2]);
double lsmWeight = Double.parseDouble(dataOnlyCombine[3]);
double totalWeight = (levinWeight + 8 * lsmWeight) / 10.0;
// perform rounding only at the end as appropriate.
// to round to two decimal places
double totalWeight2 = Math.round(totalWeight * 100) / 100.0;
答案 1 :(得分:0)
float levinWeight = Float.parseFloat(dataOnlyCombine[2]);
float lsmWeight = Float.parseFloat(dataOnlyCombine[3]);
float totalWeight = 0.1*levinWeight+0.8*lsmWeight;
DecimalFormat df = new DecimalFormat("#.##");
String totalWeightValue = df.format(totalWeight);
答案 2 :(得分:0)
如果你真的想这样做,那就使用BigDecimal。这些浮点类非常适合精度。看看他们:
默认的IEEE 746浮点数不适合您的需求。或者,您可以使用整数并将它们设为100因此: