How to safely and correctly convert a number from user input to double?

This is basically a CultureInfo problem. Formally, in my country, the decimal separator is a comma (,), and the thousands separator is a period (.). In practice, however, this is only used by accountants and diligent people. Typically, people never use the thousands separator, and they use both a comma and a period as a decimal separator. I saw that this is a problem even in some Excel spreadsheets that I received from other people, and Excel did not recognize the dot as a decimal separator, leaving a field formatted as a string, not a number.

My "solution" so far has been to simply replace all the commas in the user input with dots, and then parse the double with InvariantCulture, for example:

string userInput; ... userInput = userInput.Replace(',', '.'); double result; double.TryParse(userInput, NumberStyles.Float, CultureInfo.InvariantCulture, out result); 

This will obviously fail when someone really enters the thousands separator, and it seems to me more like a hack than a real solution. So, in addition to creating your own parser for pairs, are there any cleaner ways to solve this problem?

+4
source share
2 answers

If you use ASP.Net, you can use AjaxControlToolkit FilteredTextBox , you can also perform the task using regular expressions and pattern matching. It is almost always better to try and get standard input than to try to cope with all possible human input variables.

Some other links:
MaskedTextBox
WPF Tools FilteredTextBox

+2
source

If there are rules that can definitively determine what they mean, then you can encode the logic. With this problem, however, it is impossible to understand the intention in each case:

 1,001 === 1.001 or 1001 

In addition, although any β€œbest” logic may suggest that numbers of the type β€œ1.01” are unique, such a notation may be a typo of β€œ1001”. How likely it is depends on what data you collect.

If people rarely use the thousands separator, your existing logic seems good. However, if you want to be 100% confident in your intentions, the only way to be sure is to ask them what they meant in such cases. For instance. if someone enters 1,001 or 1.001 , then refuse the verification, but transcode it as β€œ1.001.0” (or .00 if you are dealing with currency) in order to eliminate it, forcing them to resend it.

In practice, you are likely to do more harm than good, with such an abundance of caution, because people really don't use the thousands separator. I stick to what you have.

+1
source

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


All Articles