Hello :), I need help with my function, I need to convert double to integer.
Here's example
[....]
it works fine when I test it, but when I use it in my EA, sometimes it returns strange values, or do you have any better idea how to do this? Thx :)
You are dealing with the "imprecise" nature of double arithmetic which has been discussed many times on this forum, for example in https://www.mql5.com/en/forum/116326. With at least one of your examples, there is the additional issue that MQ4 can display up to 8 decimal places using DoubleToStr(), but uses greater precision than this internally.
For example, when you multiply a double value of 0.01004 by 10, the values which are actually getting held in the double variable are as follows. MQ4 will show the final value as 1004 because it can only display up to 8DP.
0.100400000000000 1.004000000000000 10.039999999999999 100.399999999999990 1003.999999999999900
Your only option is to specify the amount of precision you want to use in your calculation, using the NormalizeDouble() function. For example, with the following function, cele_cislo(0.01004) will return 1004.
int cele_cislo(double x, int MaxPrecisionDP = 5) { x = NormalizeDouble(x, MaxPrecisionDP); while (x - MathFloor(x) != 0) { x = NormalizeDouble(x * 10, MaxPrecisionDP); } return (MathFloor(x)); }
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
Here's example
0.4 -> 4
0.0023 -> 23
0.01004 -> 1004
and here's my function:
it works fine when I test it, but when I use it in my EA, sometimes it returns strange values, or do you have any better idea how to do this? Thx :)