# Lua: Rounding numbers and then truncate

## Lua: Rounding numbers and then truncate

There is no build-in math.round() function in Lua, but you can do the following:

`print(math.floor(a+0.5))`

.

A trick that is useful for rounding at decimal digits other than whole integers is to pass the value through formatted ASCII text, and use the `%f`

format string to specify the rounding desired. For example

```
mils = tonumber(string.format(%.3f, exact))
```

will round the arbitrary value in `exact`

to a multiple of 0.001.

A similar result can be had with scaling before and after using one of `math.floor()`

or `math.ceil()`

, but getting the details right according to your expectations surrounding the treatment of edge cases can be tricky. Not that this isnt an issue with `string.format()`

, but a lot of work has gone into making it produce expected results.

Rounding to a multiple of something other than a power of ten will still require scaling, and still has all the tricky edge cases. One approach that is simple to express and has stable behavior is to write

```
function round(exact, quantum)
local quant,frac = math.modf(exact/quantum)
return quantum * (quant + (frac > 0.5 and 1 or 0))
end
```

and tweak the exact condition on `frac`

(and possibly the sign of `exact`

) to get the edge cases you wanted.

#### Lua: Rounding numbers and then truncate

To also support negative numbers, use this:

```
function round(x)
return x>=0 and math.floor(x+0.5) or math.ceil(x-0.5)
end
```