Let’s dive into the syntax, overloads, and practical applications of math.floor()
to understand how it can be utilized in your Pine Script code.
Syntax
The math.floor()
function in Pine Script can be applied in various contexts, making it a versatile tool for different types of numerical data. Here’s a breakdown of its syntax and overloads:
- Syntax:
math.floor(number) → const int
- Overloads:
math.floor(number) → input int
math.floor(number) → simple int
math.floor(number) → series int
Arguments
- number: This can be a constant (
const int/float
), input, simple, or series type variable. It represents the number you wish to round down.
Returns
- The function returns the largest integer less than or equal to the given number. This means it effectively removes any decimal part of the number, rounding it down to the nearest integer.
Practical Example
Let’s look at an example to see math.floor()
in action. Assume you have a floating-point number representing the average price of a stock, and you want to round it down to the nearest whole number for a strategy calculation.
//@version=5 indicator("Floor Example", overlay=true) averagePrice = 150.95 roundedPrice = math.floor(averagePrice) plot(roundedPrice, title="Rounded Price", color=color.red)
Walkthrough of the Code
- Indicator Declaration: We start by declaring the script version and setting the indicator’s name and overlay property.
- Variable Initialization:
averagePrice
is initialized with a float value. - Rounding Down: We apply
math.floor()
toaveragePrice
, assigning the result toroundedPrice
. - Plotting: Finally, we plot
roundedPrice
on the chart, with the title “Rounded Price” and a red color for easy visualization.
Key Features
- Function Usability:
math.floor()
is essential for scenarios where you need integer values from calculations that produce floats, ensuring your script performs as expected without decimal precision issues. - Syntax and Application: It offers flexibility with various data types, making it suitable for a wide range of numerical operations.
- Versatile Overloads: The function can handle
const
,input
,simple
, andseries
types, allowing for its use in dynamic and static contexts within your scripts.
Takeaways
math.floor()
is invaluable for rounding down numbers to the nearest integer in Pine Script.- It supports multiple data types, enhancing its utility across different script scenarios.
- By removing decimal points, it simplifies numerical data handling, especially in financial calculations where integer values are often required.
Understanding and applying math.floor()
can significantly improve the precision and efficiency of your trading strategies and indicators in Pine Script.