Limit decimals format string

Hello! Quick question (hopefully): I’m looking for the correct format string to limit decimal places without forcing extra zeros if an integer is given. Documentation on string.format isn’t very clear. Example inputs with desired output:

Input Output
5 5
3.141592654 3.14
0.000001 0
0.0883133 0.08

Bonus points if you have a clever way to round a decimal value before chopping off the extra places.

I’m not sure if you can do all of that in string.format because 5 is expected to output 5 and not 5.00 and 0.000001 expect 0 and not 0.00, but if you add a case for whole numbers, then you can just use this for the rest:

string.format("%.2f", math.floor(num*100)/100).

You can change floor to either ceil or round if you want it to always go up, or round to the nearest, but based on your table floor is what you want if you want to get 0.08 from 0.0883133

If you want the extra whole number part:

function format(num)
    local formatted = string.format("%.2f", math.floor(num*100)/100)
    if string.find(formatted, ".00") then
        return string.sub(formatted, 1, -4)
    end
    return formatted
end
5 Likes

Hm, I was sure there was a way to do it with format, but that works! I appreciate the help!

There may be a way that I don’t know of.

function Format(Number)
    local RoundedNumber = string.format("%.2f", math.floor(Number * 100) / 100)

    return string.match(RoundedNumber, "(.-)%.?0*$")
end

print(Format(3.145))
print(Format(3.14))
print(Format(3.1))
print(Format(3))

if we used the string library we could do this

EDIT:
code is edited

1 Like