str.tostring in MQL5: DoubleToString and StringFormat

Short answer

Use DoubleToString(x, digits) or IntegerToString(n) for str.tostring, and StringFormat for str.format. StringFormat uses C printf placeholders (%s, %d, %.2f), so Pine's {0}-style placeholders must be rewritten.

str.tostring turns a number into text, optionally through a format pattern such as "#.##" or format.mintick; str.format fills {0}-style placeholders. MQL5 splits the first into typed functions, DoubleToString(x, digits) and IntegerToString(n), and replaces the second with StringFormat, which uses C printf placeholders (%s, %d, %.2f). The placeholder syntax has to be rewritten; it is not compatible.

What str.tostring and str.format compute

  • str.tostring(x): the value as text; Pine chooses the decimals. Booleans give "true"/"false", na gives "NaN".
  • str.tostring(x, "#.##"): a pattern: # is an optional digit, 0 a required one, so "#.##" prints at most two decimals and "0.00" always two. format.mintick rounds to the tick size, format.percent multiplies by 100 and appends %, format.volume abbreviates (1.2K).
  • str.format("{0} at {1,number,#.##}", a, b): positional placeholders with optional number formats.

The MQL5 equivalent

The example builds the same strings from the newest bar and shows them with Comment. Every {n} becomes a typed % code, in argument order.

//@version=6
indicator("string demo", overlay=true)
plot(close, "close")
if barstate.islast
    string s1 = str.tostring(close)
    string s2 = str.tostring(close, "#.##")
    string s3 = str.tostring(close, format.mintick)
    string s4 = str.tostring(bar_index)
    string s5 = str.format("{0} closed at {1,number,#.##} on bar {2}", syminfo.ticker, close, bar_index)
    string s6 = str.format("{0,number,percent}", (close - open) / open)
    label.new(bar_index, high, s1 + "\n" + s2 + "\n" + s3 + "\n" + s4 + "\n" + s5 + "\n" + s6)
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue

double CloseBuf[];

int OnInit()
{
   SetIndexBuffer(0, CloseBuf, INDICATOR_DATA);
   return INIT_SUCCEEDED;
}

int OnCalculate(const int rates_total, const int prev_calculated,
                const datetime &time[], const double &open[],
                const double &high[], const double &low[],
                const double &close[], const long &tick_volume[],
                const long &volume[], const int &spread[])
{
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
      CloseBuf[i] = close[i];

   int last = rates_total - 1;
   // Pine: str.tostring(close)                 -> DoubleToString, pick the digits yourself
   string s1 = DoubleToString(close[last], _Digits);
   // Pine: str.tostring(close, "#.##")         -> two decimals (DoubleToString keeps trailing zeros)
   string s2 = DoubleToString(close[last], 2);
   // Pine: str.tostring(close, format.mintick) -> the symbol's digits
   string s3 = DoubleToString(close[last], _Digits);
   // Pine: str.tostring(bar_index)             -> IntegerToString
   string s4 = IntegerToString(last);
   // Pine: str.format("{0} closed at {1,number,#.##} on bar {2}", syminfo.ticker, close, bar_index)
   //       -> printf-style placeholders: %s string, %.2f double, %d integer
   string s5 = StringFormat("%s closed at %.2f on bar %d", _Symbol, close[last], last);
   // Pine: str.format("{0,number,percent}", x) has no direct form; scale and append
   string s6 = StringFormat("%.1f%%", 100.0 * (close[last] - open[last]) / open[last]);
   // Pine: "a" + str.tostring(x) -- MQL5 also allows (string)x, which prints up to 16 significant digits
   string s7 = "raw: " + (string)close[last];

   Comment(s1, "\n", s2, "\n", s3, "\n", s4, "\n", s5, "\n", s6, "\n", s7);
   return rates_total;
}

void OnDeinit(const int reason) { Comment(""); }

StringFormat is strict about types: %d needs an integer, %f a double, %s a string. A double passed to %d prints garbage rather than failing to compile. A literal percent sign is %%.

Where the two differ

PineMQL5Note
str.tostring(x)DoubleToString(x, _Digits)choose the digits explicitly
str.tostring(x, "#.##")DoubleToString(x, 2)MQL5 keeps trailing zeros (1.50 vs 1.5)
str.tostring(x, format.mintick)DoubleToString(x, _Digits)
str.tostring(x, format.percent)StringFormat("%.2f%%", x * 100)
str.tostring(n) (int)IntegerToString(n)
str.tostring(b) (bool)b ? "true" : "false"(string)b also gives "true"
str.format("{0}", s)StringFormat("%s", s)printf codes, not braces
{1,number,#.##}%.2f
str.tostring(na)DoubleToString(NaN) prints "nan"-style texttest with MathIsValidNumber first

What the Stratlate converter emits

str.tostring dispatches on the argument's type: strings pass through, integers become IntegerToString, booleans a "true"/"false" ternary, colours ColorToString, arrays the runtime's pine_arr_str. A float becomes DoubleToString(x, 2) without a format, DoubleToString(x, n) where n counts the #/0 after the point in a literal pattern, DoubleToString(x, _Digits) for format.mintick, and a scaled value with "%" for format.percent. Two limits in the current version, neither of which is noted in the report: the default of two decimals cuts forex prices short (use _Digits), and str.format is emitted as StringFormat with Pine's {0} pattern unchanged, which MQL5 does not substitute; rewrite those patterns with % codes as shown above. The example converted CLEAN despite this.

Pitfalls

  • Keeping {0} in StringFormat: the text appears with the braces in it and the arguments are ignored.
  • Formatting a price with 2 digits: EURUSD 1.08765 prints as 1.09. Use _Digits.
  • Concatenating a number without conversion: "x=" + close[i] compiles with an implicit-conversion warning and uses the default precision. Convert explicitly; see implicit conversion from number to string.
  • Passing a long to %d: use %I64d or convert to int; otherwise large values such as millisecond timestamps print wrongly.
  • Building strings on every bar in a loop over history: strings are only needed for the newest bar; formatting thousands of them per tick slows the terminal.

FAQ

What is the MQL5 equivalent of str.tostring?

DoubleToString(x, digits) for doubles, IntegerToString(n) for integers, and a ternary or (string) cast for booleans. Pine picks the decimals by itself; in MQL5 you pass them, usually _Digits for prices.

Does MQL5 StringFormat support {0} placeholders?

No. StringFormat uses printf-style codes: %s for strings, %d for int, %I64d for long, %.Nf for doubles with N decimals, and %% for a percent sign. Arguments are consumed in order.

How do I print format.mintick precision in MQL5?

DoubleToString(x, _Digits). _Digits is the number of decimals the symbol is quoted with. If the tick size is coarser than the last digit, round to the tick first and then format.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related