Limiting the number of decimals, plus removing trailing zeros

I want to write a function that limits the string representation of a number to a specific number of decimals (in this example: 3 decimals). However, I also want to remove any trailing zeros at the end. So the following numbers should be transformed into the corresponding strings:

12.34567 -> "12.345"
10.50 -> "10.5"
12.00 -> "12"
0 -> "0"

I have looked into string patterns, and found out that the pattern "%.3f" formats a number to have 3 decimals. However, that leaves trailing zeros at the end, which I want to avoid.

I could still use the pattern and then iteratively check if the last character of the string is a 0 and remove it, but then that leaves the dot behind. I could check for both dots and zeros, but then that would transform the number 50.00 into "5", unless I add an additional check to stop after the first encounter of a dot. Either way, the resulting function would look oddly complex for a seemingly simple problem.

I am wondering, is there a better way of going about this?

1 Like

Although there isn’t a format directive that will handle that for you, it’s easy enough to achieve the same thing using just a bit of string manipulation (no need to iteratively check things).

I would probably do it like this:

local function convert(n)
	local s = string.format("%.3f", n) -- format
	s = string.gsub(s, "0+$", "") -- trailing zeros
	s = string.gsub(s, "%.$", "") -- dangling decimal point
	return s
end
4 Likes