0

My app is facing some issues with some adding, subtracting, and multiplication errors when adding the same number to itself over and over. I can add numbers such as 1.5 to 1.5, but for some reason once I start using numbers such as 3.99, after a few operations of addition or subtraction, it bugs out and outputs numbers such as 19.950000000000003.

I solved the problem above by measuring the length after the . then splitting the string. However now I am getting another problem, where sometimes if you start off with 9 * 3.99 or something alike, then you subtract 3.99 over and over, sometimes it results in the following chain

35.91 -> 31.92 -> 27.93 -> 23.93

Error with subtracting 3.99 from 27.93

This should not be happening because from 27.93 it should have went to 23.94.

Could anyone help me with these problems, and maybe suggest a better way to deal with the adding/multiplication problem besides splitting the string that is displayed?

Brady Gho
  • 51
  • 5
  • https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Todd Jul 21 '20 at 15:19
  • For most part you shouldn't use the Double/Floats because their exact representation in binary is usually not possible as stated in the linked question above as well, you should use Ints/Longs to store data as for example 150cents, and when you want to output it to the end user after calculation like multiplication etc, do a double/float division to get a better representation of it in dollars. – Animesh Sahu Jul 21 '20 at 15:23
  • If you want to store exact decimals, don't use binary floating-point!  Use an integer type (`Byte`, `Short`, `Int`, `Long`, `BigInteger`), or `BigDecimal`. – gidds Jul 21 '20 at 15:45

0 Answers0