Domanda

I have google on how to get 2 decimal for a float number in java. Below are my codes. Finally here float totalWeight = 0.1*levinWeight+0.8*lsmWeight; I get the error of possible loss of precision ? I would want to first 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;
È stato utile?

Soluzione

If you are concerned about precision

  • don't use float, it has the lowest precision of any option available. I suggest using double or BigDecimal
  • use operation which involve values which can be accurately represented. 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;

Altri suggerimenti

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);

If you really want to do it like that, then use BigDecimal. Those floating point classes are perfect for precision. Take a look at them:

Default IEEE 746 floating points will not suit your needs. Alternatively, you could use integers and thread them factor 100. So:

  • 100 is equivalent to 1.00
  • 452 is equivalent to 4.52
  • 1 is equivalent to 0.01
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top