I am having problems with the java double
data type. The problem is that for some cases the result obtained is very large number of digits after the decimal point. the same calculation done on the calculator, manually hardly reached 2 digits after decimal.
the code is as follows:
public class Calculater {
public static void main(String[] args) {
// TODO Auto-generated method stub
String quantityInString="700g";
int indexOfg=quantityInString.indexOf("g");
String onlyQuantityInString=quantityInString.substring(0, indexOfg);
int onlyQuantityInInt=Integer.parseInt(onlyQuantityInString);
double perUnitCostOfThisItem=29.00;
double returnFloat=0;
returnFloat=(onlyQuantityInInt/(1000.00))*perUnitCostOfThisItem;
System.out.println("returnFloat="+returnFloat);
}
}
The program output is: returnFloat=20.299999999999997
The answer using a calculator is 20.3
I have no idea why this is happening? I have tried it in an eclipse running on laptop and also on an Android phone both show same result.