I need help with this problem. I am making a simulator with an upgrade shop that upgrades by 1.25x, but the number gets so long because of the decimals, for example, 9.31322574615x Cash. I want to abbreviate it to having only 2 decimal digits instead of so many, but I don’t know how to do it. I know how to abbreviate stuff to the thousands or millions or billions but not decimals. I can’t seem to find this problem anywhere on the dev forum. I even tried searching it on YouTube, but it just gave me info on how to do it in languages like Java or Python or C++ and not Lua. Please help me if you can and I would really appreciate it!
2 Likes
There’s no built-in way to do this, but (see below) For a solely number based approach, you can just multiply by 100, round, then divide again. A generalized function might look something like this:
local function round(number, decimalPlaces)
return math.floor(number * (10 ^ decimalPlaces) + 0.5) / (10 ^ decimalPlaces)
end
print(round(1234.567890, 2)) --> 1234.57
Edit: Here’s another approach, just for the sake of completeness:
2 Likes
There’s the %.nf
string pattern where you give the amount of decimal points for n
and f
meaning float.
For example:
local decimal = 1.2345
local str = string.format("%.2f", decimal)
decimal = tonumber(str) --// Turn it back to a number
print(decimal) --// 1.23
6 Likes
Thank you so much! This really helped me a lot and I really appreciate it!
1 Like