I Googled on how to get 2 decimals for a float number in Java. Below is my code. Finally, here float totalWeight = 0.1*levinWeight+0.8*lsmWeight;
I get the error of possible loss of precision? I would want, firstly, covert the string into float and then have it to be 2 decimal places.
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;
If you are concerned about precision
float
, it has the lowest precision of any option available. I suggest using double
or BigDecimal
0.1 * x
will give you error because 0.1
cannot be represented precisely. Using x / 10.0
will have less error.I would write something like this
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;