0

I have a database access, and one of this field is double-precision. Normally if i set in the textbox 1.71 or 1,71 the field in database should contain 1.71.

But if i execute query the value of acces'field is 171 !!.

public const string QUERY = 
        @"UPDATE TBLART 
          SET TBLART.COST = @cost
          WHERE TBLART.CODE= '1'";

var param = new DynamicParameters();
var cost = totalCost.Replace(',', '.'); //totalCost is a textbox
param.Add("cost", Double.Parse(cost), DbType.Double);

gsmconn.Execute(QUERY, param);

What i wrong ? Thanks.

puti26
  • 431
  • 3
  • 14
  • 31
  • You are using Windows forms, Web forms, MVC, WPF, ... ? – pero Mar 26 '13 at 18:29
  • 1
    ... Is `Cost` a field which will contain a currency/money value? If so, you shouldn't be using something like a double-precision field - among other things, they can't represent `0.1` exactly (if you add it together 10 times, you won't get exactly `1.0`, usually). The standard is to use a decimal/numeric at minimum, and a money type if your DB supports it. – Clockwork-Muse Mar 26 '13 at 18:54
  • +1 for using decimal. – pero Mar 26 '13 at 19:06
  • Peter Repac: I use WPF. – puti26 Mar 27 '13 at 01:35

2 Answers2

2

double.Parse will use the current thread's culture by default. I suspect your current culture uses "." as a grouping separator.

Two options:

  • Continue to use Replace as you are already doing, but then specify CultureInfo.InvariantCulture when parsing
  • Remove the replacement, and just use the current thread's culture when parsing the original value. This relies on the culture being appropriate for the user, but is probably a better solution when that's the case. (Otherwise someone entering "1,234.56" will get a parse error when they expected a value of "just a bit more than 1234".)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

If I remember correctly in windows forms you can bind an double property to a textbox and it will automatically take care of parsing and converting. You should not manually do parsing from string to double.

That problem is already solved fro you by the .NET framework.

Another suggestion, your data access code should not do any parsing. That should be done in some higher layer. But better leave it to the framework.

pero
  • 4,169
  • 26
  • 27