-1

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?

Yahya
  • 13,349
  • 6
  • 30
  • 42
MrGatzi
  • 23
  • 3
  • 1
    Use `double` instead of `float`. – Yahya Jun 02 '17 at 17:54
  • 1
    Or even better use `BigDecimal` instead of `float`. – Henry Jun 02 '17 at 17:55
  • `float` has [6 to 9 significant decimal digits precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32), and your number `1000009.00` is 9 digits long. You've exceeded the precision of `float`. Use `double` (15–17 digits) or `BigDecimal` (unlimited precision) instead. – Andreas Jun 02 '17 at 18:06
  • Generally, don't use floating point for calculations where the exact decimals in base10 are important (e.g. money), its going to bite you at some point, especially if you're not 100% certain and fluent in how floating point works in detail. – Durandal Jun 02 '17 at 18:21

2 Answers2

0

You can use BigDecimal::multiply for example :

String aa = "1000009.00";
aa = aa.replaceAll(",", ".");
BigDecimal fullValue = new BigDecimal(aa);

System.out.println("full value  = " + fullValue.multiply(new BigDecimal(100)));

Output

full value  = 100000900.00
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

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
Yahya
  • 13,349
  • 6
  • 30
  • 42