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 formats built-in and custom enum values; unnamed numeric values need not produce a declared identifier.
Explicit formatting makes signedness and display precision visible; it does not change the underlying numeric value.
Use DoubleToString(val, digits) to choose decimal display precision, not to validate a broker price or repair binary arithmetic.
StringFormat provides clean printf-style string formatting for order comments, chart overlays, and log outputs.
Essential MQL5 Type-to-String Conversion Functions
MQL5 permits several implicit conversions, including numeric-to-string conversion that can produce compiler warnings. Explicit functions make the intended representation easier to review; they do not by themselves prevent calculation errors.
The language reference provides built-in conversion functions for enums, signed integers and floating-point values. Match formatting specifiers to the actual argument types.
| 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 parameter; int widens to long | 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
Use + for simple concatenation and StringFormat when an explicit format is easier to read. Performance depends on the workload; no benchmark here establishes a universally faster method.
- Plus operator (+): string msg = "Count: " + IntegerToString(count);
- StringFormat: string msg = StringFormat("Ticket: %I64u, Price: %.*f", ticket, digits, price);
- StringAdd: appends to a referenced string and returns success; allocation behavior and speed require measurement.
Resolving Implicit Conversion Compiler Warnings
In MetaEditor, assigning a numeric variable directly to a string variable triggers warning: "implicit conversion from number to string".
IntegerToString accepts a signed long; use StringFormat("%I64u", ticket) for an unsigned 64-bit ticket without narrowing its range. DoubleToString controls display decimals; order prices still need tick-grid and broker-constraint checks.
Implementation details & mechanics
Core implementation pattern
Formatting does not impose a maximum length or guarantee that a server preserves an order comment. Keep comments short, check the actual broker behavior and store durable identifiers separately. This example only prints synthetic data; it sends no orders.
Error handling & safety rules
Use EnumToString with actual enum types such as ENUM_POSITION_TYPE. MqlTradeResult.retcode is an unsigned numeric code, not a built-in ENUM_TRADE_RETCODE type; log its number and comment or map documented TRADE_RETCODE constants explicitly.
MQL5 Code Implementation
//+------------------------------------------------------------------+
//| 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 = StringFormat("%I64u",orderTicket);
string paddedTicket = StringFormat("%010I64u",orderTicket);
Print("Ticket String: ", ticketStr, " | Padded: ", paddedTicket);
// Decimal display precision does not change the stored binary value
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 diagnosticLine = StringFormat("%s | #%I64u | %.2f lots | %s",
_Symbol,
orderTicket,
0.25,
EnumToString(InpRegime));
Print("Formatted diagnostic (not an order comment): ", diagnosticLine);
}
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 generates editable MQL5 source code. Review its logic, request a syntax check, and compile and test the final file in MetaEditor.
Frequently Asked Questions
Related MQL5 pages
Technical references
Risk and testing note
These educational examples require independent compilation and testing. A compile pass or an illustrative setting does not establish execution correctness or profitability. Any reported performance must be supported by reproducible data and test settings; past results do not predict future returns. Trading involves significant risk of loss. This content is not financial advice.