views:

87

answers:

2

Hi everyone,

I store a float number in my SQLite (through core data) like this:

unit.conversion = [NSNumber numberWithFloat:0.001];

When I look at the SQLite database the value is 0.0010000000474974513

unit.conversion is an optional float in my datamodel...

What's wrong with that?

Thanks

+5  A: 

Floating point numbers are not (always) exact representations - they are approximations.

See What Every Computer Scientist Should Know About Floating-Point Arithmetic for the background.

martin clayton
Thanks for the explanation but I need also a solution
ncohen
0.001 and the value you have in the database are, for most purposes, the same thing, as the above link probably explains. What exactly would you expect as a solution?
mrueg
the problem is that when I ll do some multiplications, I ll get float numbers with strange values...
ncohen
But you probably won't; you're going to be rounding for display, right?
Wevah
I wanted to avoid rounding all the time...
ncohen
A: 

Given the fact that what you are seeing is correct (as already answered) and you are not happy with this: You can use NSDecimalNumber. A quick google search provided:

NSDecimalNumber allows you to do decimal arithmetic like how a financial institution would like you to do math. Warning: it is a little obnoxious to work with since all math operators are messages.

Brent Priddy