Search code examples
luapercentage

LUA - How to round a percentage number?


I want to round a percentage number like if is 94.5% to show it like that. But if the number is like 10.0% or 100.0% or 40.0% to show only the number 40% without the .0

In JS is Number(percentage).toFixed(1); but idk how it is in LUA.

Any ideas?


Solution

  • You can first round up to 1 decimal sign, and then use %g to reduce the output of insignificant zeros.

    local values = {"100.0", "94.25","94.7","20.0"}
    
    for k,v in pairs(values) do
        print( string.format("%g",string.format("%.1f",v)) )  
    end
    

    out:

    100
    94.3
    94.7
    20