I have too many decimals

Please specify version and format if asking for help, or apply optional tags above:
Twine Version: 2.3.8
Story Format: sugarcube 2.31.1

I use this widget when the player makes a payment;

<<widget "MoneyDown">>\
        <<set $Money -= $args[0]>>
		<<set $MoneyNeg to $args[0]>>
        <<if $Money lte 0>>
            <<set $Money to 0>>

When making a payment I use the following code;

<<link [[Bus ticket downtown €7.80|Downtown]]>>
	<<addmins 18>>
	<<MoneyDown 7.80>>

In the Storycaption I use the following code to display the money;
You have €<<print $Money>>

The following occurs;
I have €600.
I make 2 payments of 7.80, the money is now displayed as;
You have €584.4000000000001

How can I prevent I get 000000000001?

That’s caused by how computers handle floating point (decimal) numbers. floating-point-gui.de for the nitty-gritty details.

The most robust way to fix the issue is to store the amount of money in cents instead, so you’d start with 60000 cents and make payments of 780 cents. Then you can print it as euros with <<print $Money/100>>. If handling the amounts as cents feels unwieldy you can add widgets that accept the amount in euros but handle it as cents inside the widget (e.g. in the MoneyDown widget <<set $Money -= $args[0] * 100>> and so on.)

1 Like

Juhana’s way of doing it is likely to end up as a floating-point number anyways without some modifications to prevent that.

Instead of doing your code that way, you can just use the .toFixed() method to limit your numbers to two decimal places. For example:

You have €<<= $Money.toFixed(2)>>

would display as:

You have €584.40

That will also make sure that it displays the number with two decimal places every time.

(FYI - The <<=>> macro is a shortened version of the <<print>> macro.)

Enjoy! :slight_smile:

1 Like

thx both for the solutions.
Ended up with using HiEv’s solution.