How Do I Round A Number?

Hello! I used a formula to calculate a variable.

When I display the variable it shows something like 95.3861909196. How do I round it at 95?

Thank you!

You can use: math.round( 95.386 )   :slight_smile:

How about rounding to the nearest decimal (i.e. 9.329854529  to 9.33)?

You could probably do something along these lines to get that:

math.round( (9.3298*100) ) *0.01  

The above should work for two decimals places. To one decimal you would times by 10 first and the by 0.1.

You can use this round to get a maximum number of decimal places:

-- == --    round(val, n) - Rounds a number to the nearest decimal places. (http://lua-users.org/wiki/FormattingNumbers) --    val - The value to round. --    n - Number of decimal places to round to. -- == function \_G.round(val, n)   if (n) then     return math.floor( (val \* 10^n) + 0.5) / (10^n)   else     return math.floor(val+0.5)   end end echo( round( 9.3298, 2 ) )-- prints 9.33 echo( round( 8.999, 2 ) ) -- prints 9  

Awesome, thanks.  I tend focus on the Corona documentation and often times forget to check the official Lua docs for more info. 

You can use: math.round( 95.386 )   :slight_smile:

How about rounding to the nearest decimal (i.e. 9.329854529  to 9.33)?

You could probably do something along these lines to get that:

math.round( (9.3298*100) ) *0.01  

The above should work for two decimals places. To one decimal you would times by 10 first and the by 0.1.

You can use this round to get a maximum number of decimal places:

-- == --    round(val, n) - Rounds a number to the nearest decimal places. (http://lua-users.org/wiki/FormattingNumbers) --    val - The value to round. --    n - Number of decimal places to round to. -- == function \_G.round(val, n)   if (n) then     return math.floor( (val \* 10^n) + 0.5) / (10^n)   else     return math.floor(val+0.5)   end end echo( round( 9.3298, 2 ) )-- prints 9.33 echo( round( 8.999, 2 ) ) -- prints 9  

Awesome, thanks.  I tend focus on the Corona documentation and often times forget to check the official Lua docs for more info.