EULOG1SON
EULOG1SON

Reputation: 33

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?

Upvotes: 3

Views: 1594

Answers (2)

koyaanisqatsi
koyaanisqatsi

Reputation: 2793

Rounding a floatingpoint to an integer can be done by math.ceil() or math.floor()...

> for k,v in pairs({"100.0", "94.25","94.7","20.0"}) do print(math.ceil(v)) end
100
95
95
20
> for k,v in pairs({"100.0", "94.25","94.7","20.0"}) do print(math.floor(v)) end
100
94
94
20

Upvotes: 0

Mike V.
Mike V.

Reputation: 2205

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

Upvotes: 4

Related Questions