MQL4|DataType To String Conversion Guide

In MetaTrader 4 (MT4) MQL4 programming, converting various data types to strings makes it easier to display data and output logs. This article explains how to convert Char, Double, and DateTime data types to strings in a way that’s easy for beginners to understand.

What is String Conversion?

String conversion refers to transforming various data types (Char, Double, DateTime) into human-readable string formats. This simplifies data display and log output within the program.

Char Type String Conversion

To convert Char type data to a string, use the CharToStr() function. This function converts ASCII character codes to their corresponding string.

Function Specification

string CharToStr(int char_code)
  • char_code: ASCII character code

Sample Code

int char_code = 68; // ASCII code for 'D'
string char_str = CharToStr(char_code);
Print("String: " + char_str);

Double Type String Conversion

To convert Double type data to a string, use the DoubleToStr() function. This function converts a Double type value to a string with a specified number of decimal places.

Function Specification

string DoubleToStr(double value, int digits)
  • value: Value to convert
  • digits: Number of decimal places (0–8)

Sample Code

double value = 1.23456789;
string double_str = DoubleToStr(value, 5);
Print("String: " + double_str);

DateTime Type String Conversion

To convert DateTime type data to a string, use the TimeToStr() function. This function converts DateTime type data to a string in a specified format.

Function Specification

string TimeToStr(datetime value, int mode = TIME_DATE | TIME_MINUTES)
  • value: DateTime data
  • mode: Format (TIME_DATE, TIME_MINUTES, TIME_SECONDS)

Sample Code

datetime current_time = TimeCurrent();
string time_str = TimeToStr(current_time, TIME_DATE | TIME_SECONDS);
Print("Current DateTime: " + time_str);

Execution Result

Executing the sample code above yields the following results:

String: D
String: 1.23457
Current DateTime: 2024.07.07 12:30:45

Summary

Converting various data types to strings simplifies data display and log output. In MQL4 programming, you can convert Char, Double, and DateTime data types to strings using the CharToStr(), DoubleToStr(), and TimeToStr() functions, respectively. Understanding the basic usage of these functions makes debugging and data display easier. Beginners should start by learning how to use these functions and apply them to actual trading programs.