Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating Point Number parsing: Is there a Catch All algorithm?

One of the fun parts of multi-cultural programming is number formats.

  • Americans use 10,000.50
  • Germans use 10.000,50
  • French use 10 000,50

My first approach would be to take the string, parse it backwards until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.000 would be interpreted as 10.

Another approach: if the string contains 2 different non-numeric characters, use the last one as the decimal separator and discard the others. If I only have one, check if it occurs more than once and discards it if it does. If it only appears once, check if it has 3 digits after it. If yes, discard it, otherwise, use it as decimal separator.

The obvious "best solution" would be to detect the User's culture or Browser, but that does not work if you have a Frenchman using an en-US Windows/Browser.

Does the .net Framework contain some mythical black magic floating point parser that is better than Double.(Try)Parse() in trying to auto-detect the number format?

like image 747
Michael Stum Avatar asked Aug 01 '08 19:08

Michael Stum


2 Answers

I think the best you can do in this case is to take their input and then show them what you think they meant. If they disagree, show them the format you're expecting and get them to enter it again.

like image 175
Ryan Fox Avatar answered Oct 05 '22 15:10

Ryan Fox


I don't know the ASP.NET side of the problem but .NET has a pretty powerful class: System.Globalization.CultureInfo. You can use the following code to parse a string containing a double value:

double d = double.Parse("100.20", CultureInfo.CurrentCulture); //  -- OR -- double d = double.Parse("100.20", CultureInfo.CurrentUICulture); 

If ASP.NET somehow (i.e. using HTTP Request headers) passes current user's CultureInfo to either CultureInfo.CurrentCulture or CultureInfo.CurrentUICulture, these will work fine.

like image 44
huseyint Avatar answered Oct 05 '22 14:10

huseyint