Search code examples
javafloating-pointmultiplicationfloating-accuracy

What can I do against floating point notations Errors?


I need to multiply a float by 100 in order to convert from to cents. The problem I am having is, that the value of big numbers isn't calculated correctly.

For example:

String aa = "1000009.00";
aa = aa.replaceAll(",", ".");
float bb = Float.parseFloat(aa);
bb=Math.round(bb*100);
System.out.println(bb);

What I am getting is: 1.00000896E8

So I know this is because of the way float in Java works. I have searched for an answer but people always say "use Math.round()" which doesn't work for me.

What can i do to prevent this?


Solution

  • You can use double for more precision (or BigDecimal if you expect to work with very big numbers).

    String aa = "1000009.00";
    double bb = Double.parseDouble(aa);
    bb=Math.round(bb*100);
    System.out.printf("%.2f", bb); // it prints only two digits after the decimal point
    

    Output

    100000900.00