Trouble converting string into number while also limiting decimals

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.

Examples:

Input → Output
“0.1.” → “0.1”
“0…1” → “0.1”
“…1.2.3…” → “.123”
“abc…1.2.3.” → “.123”

My current code works for removing the letters and leaving numbers and periods but I’m not sure how I can limit the decimals.

My current code:

function FormatStringToDecimal(text)
	return tostring(text):gsub('[^%d.]', '')
end

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.

1 Like

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
2 Likes

This works! Appreciate it. I wish they made string patterns a little easier to understand