MQL4|How to Compare Double Type Values

In MetaTrader 4 (MT4) MQL4 programming, comparing double type values might not always work as expected for programmers. This article explains how to compare double type values using the NormalizeDouble function in a way that’s easy to understand for beginners.

What is Comparing Double Type Values?

When comparing double type values, the nature of floating-point numbers can cause the values after the decimal point to not match exactly. This occurs due to calculation errors. For example, two values, 1.0 and 1.0, might not be equal. To solve this problem, we use the NormalizeDouble function to eliminate errors before comparing the two values.

Using the NormalizeDouble Function

Before comparing double type values, you can use the NormalizeDouble function to normalize the values, thus eliminating errors.

Function Specification
double NormalizeDouble(double value, int digits)
  • value: The value to normalize
  • digits: The number of digits after the decimal point (0-8)
Sample Code

Below is a sample code using the NormalizeDouble function to compare double type values.

double a1 = 0.001;
double a2 = 0.002;

if (NormalizeDouble(a1, 8) == NormalizeDouble(a2, 8)) {
    Print("a1 = a2");
} else {
    Print("a1 != a2");
}

Execution Result

Executing the sample code above yields the following result:

a1 != a2

Thus, using the NormalizeDouble function allows for accurate comparison of double type values.

Usage Example

Below is an example of using the NormalizeDouble function to compare double type values in an actual trading program.

Profit Calculation Example
double profit_target = 100.123456789;
double current_profit = 100.123456789;

if (NormalizeDouble(profit_target, 6) == NormalizeDouble(current_profit, 6)) {
    Print("Profit target reached.");
} else {
    Print("Profit target not yet reached.");
}

In this example, the profit target and current profit are normalized to 6 decimal places before comparison, ensuring an appropriate precision level for the comparison.

Summary

Using the NormalizeDouble function allows for accurate comparison of double type values. This ensures that value comparisons within the program are accurate and function as expected. Beginners should first learn the basic usage of this function and apply it in their actual programs.