1

I found many answer speaking about converting String to Double (with two decimals) but I'm facing a weird case. When printing the value no problem, it is right. But when I do calculations the program acts weird.

I have this code:

String str = "21.90";

I want to convert this string into a double. I tried many solution but none works properly.

double amount = Double.valueOf(str);

or

double amount = Double.parseDouble(str);

or

try {
    amount = DecimalFormat.getNumberInstance().parse(str).doubleValue();
}
catch (ParseException e){
    // error
}

I've tried also with rounding methods like:

double roundOff = Math.round(amount * 100.0) / 100.0;

Number is converted in "21.9" but when I do, for example:

System.out.println(number - 21.8) = 0.09999999999999787

I don't understand why it's doing this.

Thanks in advance for your help.

Evaluating the calculation

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
Simone Colnaghi
  • 348
  • 3
  • 9

2 Answers2

3

You are losing precision when you make calculation with double, to make calculation, it better to use BigDecimal, so instead I would go :

String str = "21.90";
BigDecimal result = new BigDecimal(str).subtract(BigDecimal.valueOf(21.8));
System.out.println(result);
=> 0.10
YCF_L
  • 49,027
  • 13
  • 75
  • 115
-1

System.out.println is using strings and the double is converted to a string . A double value has no precsion at all, even if your string has 2 decimals.

So you need to format the converted string:

String str = "21.90";
double amount = Double.parseDouble(str);
System.out.println("double is: " + amount);

double roundOff = Math.round(amount * 100.0) / 100.0;
System.out.println("double rounded is: " + roundOff);

The output is:
double is: 21.9
double rounded is: 21.9
result is: 0,10
Because of my Locale DE a comma is used in the output. Or use:

System.out.println("result is: " + String.format(Locale.US,"%.2f",amount - 21.8));

System.out.println("result is: " + String.format("%.2f",amount - 21.8));
Norbert
  • 179
  • 7