Round down to a specific decimal point

I want to round down number to a specific decimal points, sth like this:

input:
9.42
3.123
5.326
0.32

output:
9.4
3.1
5.3
0.3

How exactly do i do that?

Should work like this.

local str = "0.34415145"
local result = str:sub(1, str:find(".", 3, false),3) 
print(result) --print(tonumber(result))

Or you can do it like this

rounded = math.round(number * 10)/10

It takes your number with the decimal, multiplies by 10 to move the decimal over 1 place, rounds it to a whole number, then divided by 10 to move the decimal back.

1 Like

You may be able to use the math functions floor and ceiling. Or you can either print to string using the basics of the Lua implementation of C’s printf and limit the output to a certain number of characters. Or you could string convert the input, then truncate the decimals to an integer and round them using math.celing() or math.floor()

math.round is better since it’ll round up or down.
ceiling or floor only round down to the integer or up to the integer.
No converting to string is required.

What I did is probably inefficient but it works nicely:

local value = 3.8371

value = (math.floor(value*10))/10

print(value)
--3.8

I just realised @Scottifly also had this idea.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.