📜 ⬆️ ⬇️

What you need to remember about the decimal separator

Everyone who has ever written C # programs used such a simple function as
Convert.ToDouble(string value); 
I, like the others, had no problems with it until a certain point. This function has such a feature that not everyone knows - this is the fact that the default separator is the one that is used in the system.
image


image

In English-speaking countries, a period is used as a separator, and in other countries, mainly, a comma. Everything is in principle not bad, and the .Net environment, like most modern programs, knows exactly which separator is used by the system. But such a program as Meta Trader was written by Russian programmers, who just didn’t know about the separator, and the program always uses a comma by default. It was necessary to implement the transfer from MT4 to the data application and back over the sockets. During testing on my computer strange behavior was not noticed, because I have the system default ",". But the program was written for a foreign customer, whose idea was that everything should work in the same way. It is not clear for what reason, the data received by my program, when translated from a string to Double, were not processed correctly and without any exceptions. For example, the conversion from the string "1.4174" to the number on my computer gave the same result, while the customer "1.4174" gave the result 14174, that is, a five-digit number without any separators, which was not immediately noticed.
')
The solution, unlike the error itself, was found instantly - replace the comma with the sign used by the system.

Lines:
 String Source = "0,05"; Double number = Convert.ToDouble(Source); 

cause a FormatException in case a period separator appears in the system.

Replace them with
 Char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0]; String Source = "0,05".Replace( ',' , separator); Double number = Convert.ToDouble(Source); 

and the problem is solved, regardless of which sign is used by the system, replacing a comma in the string with this sign - we get the appropriate format for conversion.


To change the separator in the system, go here:
image
image
image

I hope you will never forget about this nuance, if you work for a foreign customer. And it will help save some time.

Source: https://habr.com/ru/post/138957/


All Articles