Hello fellow developers!
I am currently working on a project where there is a server multiplier. This server multiplier basically helps everyone on the server by multiplying their cash revenue. The problem is, when you upgrade the server multiplier, if doesn’t show the real value. Let me explain:
First of all, you see that when someone upgrades the server multiplier, they are supposed to add 0.3 to the old and new values. (which displays in game).
After upgrading multiple times, it should, theoretically display a number with only 1 decimal or just an integer, but for some reasons, it makes something like this:
So, I want to make sure that it only displays 1 digit on the text, like 1.2 or 3.6, not 3.6999999999999…
Is there a way to do this and also to make that if it’s an integer, it doesn’t displays 1.0 or 2.0?
By the way, I checked the numbers in the OldValue and NewValue NumberValues and it shows a 1 digit number, but it doesn’t display it like it should. So the problem is maybe from the GUI?
So we have this number 4.28472, multiply it by 1000, and you get 4284.72, round it and we have 4284, now divide it by 1000, and now we have the first three decimals, which are 4.284
No, you don’t understand what I mean, let me explain again…
The value, is 1.3
But the GUI shows something like 1.3000000000001 or 1.299999999999
Let’s say I round 1.3 (because it’s the real value, 1.3000000000001 isn’t)
1.3 * 10 = 13
math.round(13) = 13
13 / 10 = 1.3
So I get the same result as before: 1.3
And the GUI doesn’t change, it still shows 1.29999999999 and sometimes 1.300000000001
Quick run down, string.format lets you format strings in various ways by passing in a key and some value.
A key of “%.” tells the function to read the string, up until it locates a period.
A key of “%.1” modifies the function slightly by also returning one place after the period.
A key of “%.1f” will have the string be interpreted as a floating point number, which will allow the returned string to be rounded, based on the number that is returned.
I had this problem in my game, where you would have a number such as 100, but instead it would display 99.999… To combat this, I used string.format(). In your case, with string.format, instead of making the 99.999 a whole number, you want to format it to a float value. Here’s an example:
local valueToFormat = 12345.6789 -- number to be formatted
local format = "%.3f" -- format you want to use, this will round off your float value to 3 decimal places
local newStringValue = string.format(format, valueToFormat) -- format the string to your liking
print(newStringValue)
-- output: 12345.679