javadecimalprecision

Possible loss of precision during conversion of float number


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;

Solution

  • If you are concerned about precision

    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;