Fix possible floating point error

Hello, I am having issues with my money system, its hard to explain so I will just show pictures
player inputs value

player gets tools of seperated bank notes (correctly subtracts)
player deposits banknotes
money goes back into account and it goes to 4999.01 instead of the original value 5000, adds incorrectly.

Server script

				local updateBy = tonumber(money.Name:match('%d+'))
				if string.find(money.Name,'p') then updateBy /= 100 end
				ReplicatedStorage.RemoteEvents.UpdateMoney:FireClient(plr,math.floor(updateBy * 100 + 0.5) / 100)

money is a tool that the player can have, its name can be something like $1 or $5 or 50p

Client script

	MoneyInputGui.Money.Text = math.floor((tonumber(MoneyInputGui.Money.Text:match('%d+')) + updateBy) * 100 + 0.5) / 100

The blue part is MoneyInputGui (a textbox)
The red part is MoneyInputGui.Money

Any help is appreciated.

1 Like

I’m not exactly sure what you’re asking, but you can format a sting to 2 decimals using:

string.format("%.2f", String)
1 Like

Tried that, didn’t work, the problem is that
this is a 4999.01 after adding the amount that was subtracted earlier, it should be 5000 because there are no missing bank notes here

What happens if you use math.round instead of your code of math.floor and +.5?
Any time you do a calculation like this it may not hurt to round the individual numbers before the calculations and then the final result at the end rather than just round the end value.


I found out that


only outputted whole integers, not full floating point values or decimals, which was the cause of the issue, this wasn’t even a floating point error which I thought it was

So it when it came to the addition, it was adding, say, 0.1 to 4999 when it was meant to be adding 0.1 to 4999.9

The solution was this


This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.