double.Parse makes a wrong integer value discarding the floating point
This issue is found on Windows 7 Home Basic Greek version, which is, say, given a string with floating point number, like "0.029", to double.Parse() API, and I get 29 as the result, and given "1.11" to double.Parse() then I get 111. I tried Convert.ToDouble() and I get the same wrong answer. The attached file is the log file from our product. ConsoleFile20180726.txt
@zhangguofu Out of curiosity, what is your locale? In many countries the , is the decimal placeholder. Can you try replacing the period . with a comma , and see if the behavior persists?
@AaronRobinsonMSFT Thanks for your information, it turns out that it is exactly the root cause for this issue, that in Greece, comma is used instead of period for the decimal placeholder. Once it is modified to be the period, this issue goes away. But I think this is a common issue that many international applications might encounter with. It is a common practice that configuration files are used for customization convenience, and some floating point numbers might be in these configuration files, once the content is converted to use in different countries, this issue might come up. So what is the best way to handle this challenge? Is there a way to know all the possible formats over the world?
You can pass a culture into double.Parse, for example:
double.Parse("0,029", new CultureInfo("el-GR"))
So the way to handle it is to know what culture the string was written in. For configuration files you should be able to control it, and I would recommend the invariant culture (which is broadly English).
double.Parse("0.029", CultureInfo.InvariantCulture);
If you really are parsing strings from users that are expected to be from different locales, then your application needs to be strongly aware of it.
@zhangguofu As @GalaxiaGuy mentioned, applications that run in various locales must be designed with that in mind. I can speak from personal experience that properly designing an application to be locale aware and 'do the right thing' is incredibly hard. Microsoft has many tenets around proper localization and uses C# heavily internally so there is great support in the API surface area, but that does mean the design of the application needs to incorporate that knowledge. Microsoft has documentation on this, but requires significant design to get right.
@GalaxiaGuy @AaronRobinsonMSFT Thanks for your sharing, helps us a lot, thanks again.