Why does my number change when I convert it from a decimal into a float?
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?
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
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.
精彩评论