Pine Script String Formatting

Pine Script Float to String: Type Conversion and str.tostring() Guide

In Pine Script v6, converting numeric values (floats and integers) to strings is performed using the str.tostring() function. The function accepts a number and an optional format pattern such as format.mintick, format.percent, or custom decimal masks like "#.##". To parse strings back into numeric values, use str.tonumber(). For combining multiple strings, Pine Script supports the + operator and the str.format() templating engine.

Format Strings with AI

Formatting patterns with str.tostring in Pine Script v6

Formatting numbers accurately is essential when constructing on-chart labels, table cells, or dynamic JSON alert payloads for automated webhook execution.

Code expressionSample valueFormatted string outputBest used for
str.tostring(close, format.mintick)452.12999"452.13" (if tick is 0.01)Trade entry prices and stop loss orders
str.tostring(0.045, format.percent)0.045"4.5%"Return metrics, slippage rates, and drawdown figures
str.tostring(volume, "#,###")1450200"1,450,200"Large integer counts and volume metrics
str.tostring(rsi, "#.#")64.789"64.8"Oscillator readings in compact table headers

Complete Pine Script v6 script: JSON webhook and status label generator

The following Pine Script v6 script demonstrates how to format prices and variables to generate formatted text labels on the chart and construct clean JSON strings for external trading webhooks.

Pine Script v6: Dynamic string conversion and JSON payload builderpinescript
//@version=6
indicator("String Formatting & Webhook Builder [v6]", overlay = true)

// Inputs
float stopMultiplier = input.float(1.5, "Stop ATR Multiplier", minval = 0.5)
string actionType = input.string("BUY", "Order Action", options = ["BUY", "SELL"])

// Calculations
float atrVal = ta.atr(14)
float stopPrice = actionType == "BUY" ? close - (atrVal * stopMultiplier) : close + (atrVal * stopMultiplier)

// Format numbers with tick precision
string priceStr = str.tostring(close, format.mintick)
string stopStr = str.tostring(stopPrice, format.mintick)
string timeStr = str.format_time(time, "yyyy-MM-dd HH:mm", "UTC")

// Construct multi-line on-chart dashboard text using str.format
string displayText = str.format(
     "Status: {0}\nPrice: {1}\nStop: {2}\nTime: {3}", 
     actionType, priceStr, stopStr, timeStr)

// Render on-chart label on current bar
var label statusLabel = na
if barstate.islast
    label.delete(statusLabel)
    statusLabel := label.new(
         bar_index, high, displayText, 
         color = color.navy, textcolor = color.white, 
         style = label.style_label_down)

// Generate JSON alert payload for webhook dispatch
string jsonPayload = str.format(
     '{{"action":"{0}","symbol":"{1}","price":{2},"stop":{3},"timestamp":"{4}"}}', 
     actionType, syminfo.ticker, priceStr, stopStr, timeStr)

// Trigger condition example
bool signal = ta.crossover(close, ta.ema(close, 20))
if signal
    alert(jsonPayload, alert.freq_once_per_bar_close)

String concatenation: Plus (+) operator vs str.format

When joining multiple pieces of text in TradingView Pine Script, developers choose between two approaches:

  • str.format templating: Recommended for complex strings and JSON payloads. It keeps templates readable by replacing numbered tokens ({0}, {1}) with corresponding variables.
  • Plus (+) concatenation: Best for short combinations like "RSI: " + str.tostring(rsiVal). Note that all joined elements must already be of type string; joining a float directly with a plus sign causes a compiler error.
  • Escaping quotes: When writing JSON strings, double up curly braces in str.format (e.g. {{ and }}) so the template engine does not confuse them with variable placeholder tokens.
  • Converting strings back to numbers: Use str.tonumber(str). If the string cannot be parsed as a valid number, the function cleanly returns na.

Handling type casting errors in Pine Script v6

Watch out for these common type compatibility issues:

  • Implicit conversion missing: Pine Script does not automatically convert numbers to strings inside string expressions. You must explicitly call str.tostring(x).
  • Legacy tostring() syntax: In v4 and earlier, tostring() had no namespace. Pine Script v5 and v6 require str.tostring().
  • Color to string: Colors cannot be converted to strings with str.tostring(). Manage color states using conditional branches rather than string tags.
Where Pineify fits

Pine Script AI Coding Agent

Generate webhook JSON alerts, dynamic on-chart dashboards, and error-free Pine Script v6 string formatting with Pineify AI.

Also useful: Visual Pine Editor. Configure webhook alerts and chart display panels visually without memorizing formatting masks.

Format Strings with AI

Frequently asked questions

String formatting and webhook payloads must match external receiving service specifications. Always test webhook alerts in demo accounts before linking live order execution bots.

Sources and verification