WoW:USERAPI round: Difference between revisions

From AddOn Studio
Jump to navigation Jump to search
m (New page: {{userfunc}} <!-- Leave this line in! --> Round a number off to n places. number = round(input, n) == Function Parameters == === Arguments === ;input : Number. The number to round ;n : ...)
 
m (Move page script moved page USERAPI round to USERAPI round without leaving a redirect)
 
(5 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{userfunc}} <!-- Leave this line in! -->
{{userfunc}} <!-- Leave this line in! -->


Round a number off to n places.
 
  number = round(input, n)
'''Round''' a number off to n places.
  number = round(number, decimals)


== Function Parameters ==
== Function Parameters ==
=== Arguments ===
=== Arguments ===
;input : Number. The number to round
;number: Number. The number to round.
;n : Number. Round to this many places. If nil, round to 0 places.
;decimals : Number. Round to this many places.
=== Returns ===
=== Returns ===
; number : Number. The rounded number.
;number : Number. The rounded number.


== Example ==
== Example ==
  local number = round(math.pi, 2)
  local number = round(math.pi, 3)
  print(number) -- prints 3.14
  print(number) -- prints 3.142


==Code==
==Code==
<pre>function round(input, places)
<!-- No, no sanity checks are needed. That's the programmers responsibility. -->
     if not places then
<pre>function round(number, decimals)
        places = 0
     return (("%%.%df"):format(decimals)):format(number)
    end
    if type(input) == "number" and type(places) == "number" then
        local pow = 1
        for i = 1, ceil(places) do
            pow = pow * 10
        end
        return floor(input * pow + 0.5) / pow
    end
end</pre>
end</pre>
== See Also ==
* [[truncate]]
__NOTOC__
__NOTOC__

Latest revision as of 04:49, 15 August 2023

This page documents a user-defined function that you can copy and paste into your addon. Replace PREFIX with your addon or lib prefix to avoid conflicts between different versions of these functions.

User defined functions


Round a number off to n places.

number = round(number, decimals)

Function Parameters

Arguments

number
Number. The number to round.
decimals
Number. Round to this many places.

Returns

number
Number. The rounded number.

Example

local number = round(math.pi, 3)
print(number) -- prints 3.142

Code

function round(number, decimals)
    return (("%%.%df"):format(decimals)):format(number)
end

See Also