Inaccurate calculation of variables

I’m building a money game, where I add 0.1 to the variable “Totalmoney” when I click on a 10 cents coin.
First click works fine, second click works fine, but clicking three times gives me a value of 0.30000000000000004.

Why is this happening?

Approj file:
MoneyGame.approj (1.2 MB)

Why this happens

Computers store decimal numbers in binary format.

  • Some numbers, like 0.1, cannot be represented exactly in binary.

  • Therefore, 0.1 + 0.1 + 0.1 does not exactly equal 0.3; it becomes 0.30000000000000004.

  • This is called a floating-point precision issue.


Solution (in ActivePresenter)

  1. On the OnClick action, after you already use Adjust Variable → TotalMoney + 0.1,

  2. Add an Execute JavaScript action and paste the following code:

// Get the TotalMoney variable
var total = prez.variable("TotalMoney");

// Round to 2 decimal places
total = Math.round(total * 100) / 100;

// Assign the updated value back to ActivePresenter variable
prez.variable("TotalMoney", total);

  • This code rounds the TotalMoney variable to 2 decimal places on every click.

  • Now 0.1 + 0.1 + 0.1 will correctly display as 0.3 instead of 0.30000000000000004.

2 Likes

@BurhanBey- I see you beat me to the keyboard. :grinning_face:
I was typing a response when yours popped up…

@Koen This is frustrating but it is simply something we have to deal with.
I just want to be clear – This is NOT an ActivePresenter bug.

3 Likes