round

function round( x, n ) --> res

Description

Rounds x to a specified number with n digits.

Parameters

x

The number that should be round.

n

The number of digits to which you want to round x.

Return Values

res

The rounded number.

Code

--ZFUNC-round-v1
local function round( x, n ) --> res
   if x > 0 then
      return math.floor( x * math.pow( 10, n ) + 0.5 ) / math.pow( 10, n )
   else
      return math.ceil( x * math.pow( 10, n ) - 0.5 ) / math.pow( 10, n )
   end
end

return round

Examples

local t = require( "taptest" )
local round = require( "round" )

t( round( 2.15, 1 ), 2.2 )
t( round( 2.149, 1 ), 2.1 )
t( round( -1.475, 2 ), -1.48 )
t( round( 21.5, -1 ), 20 )
t( round( 626.3, -3 ), 1000 )
t( round( 1.98, -1 ), 0 )
t( round( -50.55, -2 ), -100 )

t( round( 0, 2 ), 0 )
t( round( 0, -2 ), 0 )

t()

Inspired by

See also