1

using c# mvc4 and mssql I have an Object which has a float field, now when I look it in the database the float value is 2.014112E+17 but when I get the object in my code, it becomes 2.01411186E+17. why is it different between the object in the server and the object in the database? there is no conversion happening in between by me, just reading an object from database. Thank you

Edit: I'm using this float point as a timestamp to sync some of my data with another database and this issue is causing is me some problems, is there a way to get an accurate value or storing it as a float is a wrong idea in first place?

arash moeen
  • 4,533
  • 9
  • 40
  • 85

2 Answers2

5

Floats are only accurate to a certain degree due to their implementation. For accuracy, use Decimal.

Difference between decimal, float and double in .NET?

float and double are floating binary point types. In other words, they represent a number like this:

10001.10010110011

The binary number and the location of the binary point are both encoded within the value.

decimal is a floating decimal point type. In other words, they represent a number like this:

12345.65789

Edit: You can also try saving the timestamp as a unix timestamp, which is just the number of seconds since 1970-01-01. It might be better suited for your needs

Community
  • 1
  • 1
user1666620
  • 4,800
  • 18
  • 27
  • I'm getting the timestamp like decimal.Parse(DateTime.Now.ToString("yyyyMMddHHmmss"));. is there a chance that the value will be bigger than the decimal range? – arash moeen Nov 18 '14 at 14:16
  • @arashmoeen - the value being out of range would depend on how you define the decimal. Up to you to figure out what your needs are. – user1666620 Nov 18 '14 at 14:25
  • I'd rather to go with your unix timestamp solution which I wasn't aware of, I'll get the total seconds like "long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;" which should do the job for me as I wanted. can you please edit you answer including the unit timestamp solution so I can accept it as answer? – arash moeen Nov 18 '14 at 14:27
4

If you have literally used a SQL float with a C# float, these are not comparable. You should be using a SQL real to store your C# float.

See here for full chart: C# Equivalent of SQL Server DataTypes

As an aside, you will always have the potential for these issues when working with floating point numbers. Where possible, use a decimal instead.

Further reference for SQL float != C# float: Why is a SQL float different from a C# float

Community
  • 1
  • 1
Steve Lillis
  • 3,263
  • 5
  • 22
  • 41