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(4.5, format.percent)4.5 percentage points"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

This indicator formats a label and builds a sample JSON message after ATR is available. The signal is a confirmed close crossing above its EMA; the BUY/SELL input only labels the message and does not implement a short-entry rule. It places no orders. Create a TradingView alert for alert() calls, then inspect the received payload against your receiver schema before enabling any execution.

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)

// Escape the two JSON string metacharacters that can occur in a symbol.
string symbolJson = str.replace_all(str.replace_all(syminfo.tickerid, "\\", "\\\\"), '"', '\\"')
string jsonPayload = '{"action":"' + actionType + '","symbol":"' + symbolJson + '","price":' + priceStr + ',"stop":' + stopStr + ',"timestamp":"' + timeStr + '"}'

// A sample close-confirmed alert, not a complete trading system.
float ema20 = ta.ema(close, 20)
bool signal = ta.crossover(close, ema20)
if signal and barstate.isconfirmed and not na(atrVal)
    alert(jsonPayload, alert.freq_once_per_bar_close)

Percentage units and JSON validity

format.percent appends a percent sign to a value already expressed in percentage points. For a fractional return such as 0.045, multiply by 100 first or use a custom trailing-percent mask such as #.##%. An unavailable value formats as NaN, which is not a valid unquoted JSON number; the alert below waits for ATR. Its UTC time string is a display format, not a timezone-bearing ISO 8601 timestamp.

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.
  • Literal braces: str.format uses apostrophe-quoted text for literal braces, not doubled braces. The example concatenates JSON fragments instead and escapes backslashes and quotation marks in the symbol string.
  • 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

Draft Pine Script formatting and alert code with Pineify AI, then compile the result and test the actual output against the intended receiver schema.

Also useful: Visual Pine Editor. Explore supported visual indicator and alert settings. Custom JSON schemas or display layouts may require code.

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