Search code examples
pine-scriptpine-script-v5tradingview-api

Is there any way in Pinescript to round to a specific number?


Is there any way to round to a specific number, say to the closest increment of 5? For example, 414.2 to 415 138.5 to 140 112.1 to 110

I know Pinescription has basic ceiling and floor functions, but nothing specifying particular units.


Solution

  • There is no built-in function for this but this is a simple math question. You can write your own function for it.

    Simply divide the number by 5 and round it. This way you would eliminate the decimal points. And then multiply by 5 again.

    //@version=5
    indicator("My script", overlay=true)
    
    f_round(num, div) => (div * (math.round(num / div)))
    
    div = 5
    num1 = 414.2
    num2 = 138.5
    num3 = 112.1
    num4 = 100
    num5 = 112.5
    
    if (barstate.islast)
        s1 = "Num: " + str.tostring(num1) + " -> " + str.tostring(f_round(num1, div))
        s2 = "Num: " + str.tostring(num2) + " -> " + str.tostring(f_round(num2, div))
        s3 = "Num: " + str.tostring(num3) + " -> " + str.tostring(f_round(num3, div))
        s4 = "Num: " + str.tostring(num4) + " -> " + str.tostring(f_round(num4, div))
        s5 = "Num: " + str.tostring(num5) + " -> " + str.tostring(f_round(num5, div))
        s = s1 + "\n" + s2 + "\n" + s3 + "\n" + s4 + "\n" + s5
    
        label.new(bar_index, high, s, textcolor=color.white)
    

    enter image description here