1

I am storing a decimal point from a textbox into a variable like this:

 decimal hiOld = Decimal.Parse(hiCommOld.Text);

So, basically hiOld is storing something like this: 46.88. But when I am doing this:

 ev.hiOldNew = (float)hiOld;

My system is storing 45.6677878899988 (something like this) number in the DB. My DB type is Float. All I want to store this variable as 46.88 into the DB.

How should I do this?


Related: Difference between decimal, float and double in .NET?

Community
  • 1
  • 1
RG-3
  • 6,088
  • 19
  • 69
  • 125
  • if I Try `float f = (float)Decimal.Parse(46.88);` it works fine and I have `46.88`. If you are using `SqlParameter`, try playing with `Scale` and `Precision` values. – Bala R May 09 '11 at 21:40

2 Answers2

3

You are actually making a great illustration of why we need a decimal type. Floating point types do not hold an exact representation of a number except for a few numbers that meet specific requirements. It is, by its nature, an approximation. So the number you are seeing is a close approximation to the one you want.

Decimal is a fixed point type that gives exact representation, the downside being that it does not have the dynamic range that a double does.

However, the solution to your problem is simply to use the correct type in your database. Assuming you are using SQL Server you need the decimal type:

http://msdn.microsoft.com/en-us/library/ms187746.aspx

Fred Thomas
  • 934
  • 3
  • 10
  • 16
  • 1
    Decimal fractions are an approximation as well, there are just *different* specific requirements as to what numbers they can represent exactly. Case in point: 1/3 – Michael Borgwardt May 09 '11 at 21:52
1

My DB type is Double. All I want to store this variable as 46.88 into the DB.

These two sentences contradict each other. If you want to store decimal values exactly in a DB, use the DECIMAL or NUMERIC database types. That's what they're for.

Read The Floating-Point Guide for details.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720