Hi so this might be a simple question but I’m wondering how I can convert a string into a number while limiting the amount of decimals that can be used to just the first one.
Use string.format with %.2f%, where 2 is the number of decimal places.
local function FormatStringToDecimal(text)
local N = tostring(text):gsub('[^%d.]', '')
return ("%.2f"):format(N)
end
print(FormatStringToDecimal("abs 0.0202294972472")) -- 0.02
if well, this works, all numbers will have 0 too many.
print(FormatStringToDecimal("abs 2")) -- 2.00
you can remove them
local function FormatStringToDecimal(text)
local N = tostring(text):gsub('[^%d.]', '')
local Format = ("%.2f"):format(N)
return Format:gsub(".00$", "")
end
print(FormatStringToDecimal("abs 0.0202294972472")) -- 0.02
print(FormatStringToDecimal("abs 2")) -- 2
the amount of 0 in return Format:gsub(".00$", "") depends on the number you used to replace 2.
I’m not sure I had the right words for the question but yours works fine until I try to format something with multiple periods. I’m trying to format something like 1........1 to 1.1. When i try this I’m getting this error: (number expected, got string)
local function StripDecimalPoints(Value)
return string.gsub(Value, "(%d+)%.+(%d+)", "%1.%2")
end
local Result = StripDecimalPoints("1........1")
print(Result) --1.1
Result = StripDecimalPoints("11")
print(Result) --11