In pine script there is a function round(x). It is very simple and allows you to round numbers only to the closest integer number.
x = round(12.26) // = 13
This is a bit irritating because I very often have to round numbers to some decimal places and not an integer.
So I created 2 functions I use all the time and now sharing them with you.
- roundn – rounds the values in its first argument to the specified number of decimal places.
- roundtick – rounds the values to current symbol mintick
Here is the code for these functions:
roundn(x, n) => mult = 1 if n != 0 for i = 1 to abs(n) mult := mult * 10 n >= 0 ? round(x * mult) / mult : round(x / mult) * mult roundtick(x) => round(x / syminfo.mintick) * syminfo.mintick
Here is how it works:
- roundn(12.76543, 0) = 13
- roundn(12.76543, 2) = 12.77
- roundn(12.76543, -1) = 10
- roundtick(9090.2467) = 9090.25 (for bitcoin on bitstamp)
Here you can find an example of these functions use.