MQL5 String Conversion Guide: EnumToString, Number Conversions & Formatting
Master MQL5 string conversion and formatting. Convert enums with EnumToString, numbers with IntegerToString and DoubleToString, concatenate strings with StringFormat, and eliminate compiler conversion warnings.
What this MQL5 guide covers
EnumToString converts any native or custom enum value into its readable code identifier string.
Avoid implicit number-to-string conversions which trigger compiler warnings and cause precision truncations.
Use DoubleToString(val, digits) with explicit symbol digits to avoid trailing floating-point inaccuracies.
StringFormat provides clean printf-style string formatting for order comments, chart overlays, and log outputs.
Essential MQL5 Type-to-String Conversion Functions
MQL5 is a strongly typed C++-like language. While MQL4 frequently allowed silent implicit conversions, MQL5 enforces explicit conversions to prevent algorithmic trading calculation bugs.
The standard library provides purpose-built conversion functions for enums, integers, and floating-point doubles.
| Conversion Function | Input Type | Return Type | Example Output |
|---|---|---|---|
| EnumToString(val) | Enumeration enum | string | EnumToString(POSITION_TYPE_BUY) -> "POSITION_TYPE_BUY" |
| IntegerToString(val, len, fill) | long / int / ulong | string | IntegerToString(105, 5, '0') -> "00105" |
| DoubleToString(val, digits) | double | string | DoubleToString(1.08456, 4) -> "1.0846" |
| StringToDouble(str) | const string | double | StringToDouble("1.0850") -> 1.085000 |
| StringToInteger(str) | const string | long | StringToInteger("100234") -> 100234 |
| StringLen(str) | const string | int | StringLen("Pineify") -> 7 |
String Concatenation: Plus Operator vs StringFormat
MQL5 offers multiple approaches to combine strings. For simple phrases, the + operator suffices. For complex diagnostic logs with mixed numbers, prices, and timestamps, StringFormat is vastly superior in readability and execution efficiency.
- Plus operator (+): string msg = "Ticket: " + IntegerToString(ticket);
- StringFormat: string msg = StringFormat("Ticket: %I64u, Price: %.*f", ticket, digits, price);
- StringAdd: In-place string appending without allocating temporary string buffers in loops.
Resolving Implicit Conversion Compiler Warnings
In MetaEditor, assigning a numeric variable directly to a string variable triggers warning: "implicit conversion from number to string".
In financial systems, implicit double conversions can round prices unexpectedly. Always wrap numeric variables in IntegerToString() or DoubleToString(val, _Digits) to make your intent explicit to the compiler.
Implementation details & mechanics
Core implementation pattern
When formulating order comments or logging trade execution, always format strings explicitly: use StringFormat("Magic_%I64u_v%s", InpMagicNumber, InpVersion) to construct safe, non-truncated comments that stay within the broker’s 31-character comment limit.
Error handling & safety rules
When logging position closures or error events, convert ENUM_TRADE_RETCODE and ENUM_POSITION_TYPE using EnumToString(). This outputs clear, searchable log entries in the MT5 Experts tab rather than opaque numeric codes.
MQL5 Code Implementation Code
//+------------------------------------------------------------------+
//| StringConversionGuide.mq5 |
//| Copyright 2026, Pineify Guides Series |
//| https://pineify.app |
//+------------------------------------------------------------------+
#property copyright "Pineify Guides Series"
#property link "https://pineify.app/mql5/string-conversion-guide"
#property version "1.00"
#property script_show_inputs
// Example custom enum
enum ENUM_STRATEGY_REGIME
{
REGIME_TREND_FOLLOWING = 1, // Trend Following
REGIME_MEAN_REVERSION = 2, // Mean Reversion
REGIME_BREAKOUT = 3 // Volatility Breakout
};
input ENUM_STRATEGY_REGIME InpRegime = REGIME_TREND_FOLLOWING;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
Print("--- 1. Enum to String Conversion ---");
// Convert built-in MQL5 enums
ENUM_POSITION_TYPE posType = POSITION_TYPE_BUY;
ENUM_TIMEFRAMES tf = PERIOD_H1;
Print("Built-in Position Type: ", EnumToString(posType));
Print("Built-in Timeframe: ", EnumToString(tf));
// Convert custom user-defined enum
Print("User Defined Strategy: ", EnumToString(InpRegime));
Print("--- 2. Numbers to String Conversion ---");
// Integer to String with zero-padding
ulong orderTicket = 8945201;
string ticketStr = IntegerToString(orderTicket);
string paddedTicket = IntegerToString(orderTicket, 10, '0');
Print("Ticket String: ", ticketStr, " | Padded: ", paddedTicket);
// Double to String with exact decimal precision
double rawPrice = 1.0845672;
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
string priceStr = DoubleToString(rawPrice, digits);
PrintFormat("Raw double: %.7f -> DoubleToString with %d digits: %s",
rawPrice, digits, priceStr);
Print("--- 3. String to Numbers (Parsing) ---");
string inputPriceStr = "2745.80";
string inputLotsStr = "150";
double parsedPrice = StringToDouble(inputPriceStr);
long parsedLots = StringToInteger(inputLotsStr);
PrintFormat("Parsed double: %.2f | Parsed integer: %I64d",
parsedPrice, parsedLots);
Print("--- 4. String Length and Concatenation ---");
string baseText = "Pineify MQL5 Code Generator";
int textLen = StringLen(baseText);
PrintFormat("String: '%s' (Length: %d chars)", baseText, textLen);
// Formatting complex string with StringFormat (printf style)
string orderComment = StringFormat("%s | #%I64u | %.2f lots | %s",
_Symbol,
orderTicket,
0.25,
EnumToString(InpRegime));
Print("Formatted Order Comment: ", orderComment);
}
Copy this code into MetaEditor, save it in your MQL5 folder (Experts, Scripts, or Include), and compile with F7.
Generate custom MQL5 code with Pineify AI
Describe the trade execution, indicator calculations, risk management, or data processing logic you need. Pineify produces clean, typed MQL5 source code ready to compile in MetaEditor.
Frequently Asked Questions
Related MQL5 pages
Technical references
Risk and testing note
Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.