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.
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)
On the OnClick action, after you already use Adjust Variable → TotalMoney + 0.1,
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.