0

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.

arco444
  • 22,002
  • 12
  • 63
  • 67

3 Answers3

0

If you need to know the reason why double acts like that the look at this

To format your double you can do it by

String.format("%.2f", floatValue);

Note this formats it till 2 places.

You can also use DecimalFormat. One way to use it:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

Another one is to construct it using the #.## format.

Community
  • 1
  • 1
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
0

Try this:

float finalValue = Math.round( value * 100.0 ) / 100.0;

Juan Aguilar Guisado
  • 1,687
  • 1
  • 12
  • 21
0

Try this for precise calculations. BigDecimal is more accurate than double.

    String quantityInString="700g";
    int indexOfg=quantityInString.indexOf("g");
    String onlyQuantityInString=quantityInString.substring(0, indexOfg);
    BigDecimal onlyQuantityInInt= new BigDecimal(onlyQuantityInString);

    BigDecimal perUnitCostOfThisItem= new BigDecimal("29.00");
    BigDecimal returnFloat= new BigDecimal(onlyQuantityInString);
    returnFloat = returnFloat.divide(new BigDecimal("1000"));
    returnFloat = returnFloat.multiply(perUnitCostOfThisItem);
    System.out.println("returnFloat="+returnFloat);

If you need precise calculations BigDecimal should be used rather than float and double.

The output for this code is: returnFloat=20.300

brso05
  • 13,142
  • 2
  • 21
  • 40