Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double is not stored correctly in MySQL database

Tags:

c#

mysql

I have an MVC application which has a restful service that updates latitude and longitude to the database. I am sending the values to the API as string and its converted to Double before it is stored in database as Double. Here is the code I am using to convert string to double:

Double _latitude, _longitude;
try
{
     Double.TryParse(lattitude, NumberStyles.Any,CultureInfo.CurrentCulture, out _latitude);
     Double.TryParse(Longtitude, NumberStyles.Any,CultureInfo.CurrentCulture, out _longitude);
}
catch(Exception e)
{
     _latitude = 0;
     _longitude = 0;
}

When its stored in database I am missing decimal points. For example:

53.345634 is stored as 53345634

I have this working on development environment running on Windows 2012. But when its moved to Windows 2008 production server I am seeing this issue.

like image 591
Zach Avatar asked Oct 19 '22 10:10

Zach


1 Answers

Specifying correct IFormatProvider/CultureInfo

The behavior that you observed might be caused by the fact that two machines have different CurrentCultures. Default value of CurrentCulture depends on a version of Windows.

To get consistent results across various machines, you should provide a specific CultureInfo (or any other class implementing IFormatProvider) for Parse or TryParse method, e.g.

// using System.Globalization;
double value = Double.Parse(stringValue, CultureInfo.InvariantCulture); 

or

double valueUsEnglish = Double.Parse(stringValue, new CultureInfo("en-US"));

Parse method uses a culture-specific decimal point symbol and group-separator symbol. In some languages (e.g. in English) decimal point symbol is a dot whereas in others (e.g. in Polish) it's a comma. Group-separator symbols are also different in various languages.

If 53.345634 is parsed as 53345634, your computer uses a culture where dot is a group-separator.

Parse vs TryParse

You should also think whether using Parse of TryParse method is more appropriate.

If during normal operation your program expects invalid output (e.g. it a user-provided value), you should definitely use TryParse and inspect returned value. TryParse returns a bool indicating whether parsing was successful and doesn't throw exceptions.

If the value that you are parsing should never be wrong (e.g. you are parsing resources that bounded with your program) you can use Parse. If you have some way to recover or provide some additional information to the user, you can catch appropriate exceptions. According to documentation possible exceptions are: ArgumentNullException, FormatException and OverflowException.

like image 147
Tomasz Maczyński Avatar answered Oct 21 '22 06:10

Tomasz Maczyński