MQL4 String Double Formatting Lesson
Learn how to format double values with thousands separators in MQL4 for better readability in trading applications.
Formatting Doubles with Thousands Separators in MQL4
In MQL4 (MetaTrader 4's programming language), formatting double values (e.g., 1234567.89) with thousands separators (e.g., 1,234,567.89) enhances readability, especially for financial data like account balances or trade profits. MQL4 doesn't have a built-in function for this, but we can use the StringFormat()
function or custom logic to achieve it.
Key Concepts
double
: A data type for decimal numbers (e.g., 1234567.89).StringFormat()
: Formats numbers into strings with specified patterns.- Thousands Separator: Typically a comma (,) or period (.) based on locale.
Example Code
void OnStart() { double number = 1234567.89; string formatted = FormatNumberWithThousands(number); Print("Formatted Number: ", formatted); // Output: Formatted Number: 1,234,567.89 } string FormatNumberWithThousands(double value) { string result = StringFormat("%.2f", value); // Format with 2 decimal places int decimalPos = StringFind(result, "."); string integerPart = StringSubstr(result, 0, decimalPos); string decimalPart = StringSubstr(result, decimalPos); string formattedInteger = ""; int len = StringLen(integerPart); for(int i = 0; i < len; i++) { formattedInteger = StringSubstr(integerPart, len - 1 - i, 1) + formattedInteger; if((i + 1) % 3 == 0 && i + 1 < len) formattedInteger = "," + formattedInteger; } return formattedInteger + decimalPart; }
Explanation
1. Input: We start with a double value, e.g., 1234567.89
.
2. StringFormat(): Converts the double to a string with 2 decimal places (1234567.89
).
3. Split: Separate the integer part (1234567
) and decimal part (.89
).
4. Formatting: Loop through the integer part backwards, adding commas every 3 digits.
5. Output: Combine the formatted integer part with the decimal part to get 1,234,567.89
.
Try It Yourself
Copy the code into MetaTrader 4's MetaEditor, compile it, and run it in a script to see the result in the Experts tab.
Example Output:
1,234,567.89