2

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

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Nate
  • 7,606
  • 23
  • 72
  • 124

2 Answers2

5

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
  • 76,436
  • 32
  • 213
  • 198
  • Thanks for the explanation but I need also a solution – Nate Sep 21 '10 at 22:56
  • 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 Sep 21 '10 at 23:01
  • the problem is that when I ll do some multiplications, I ll get float numbers with strange values... – Nate Sep 21 '10 at 23:12
  • But you probably won't; you're going to be rounding for display, right? – Wevah Sep 22 '10 at 02:07
1

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.

Community
  • 1
  • 1
Brent Priddy
  • 3,817
  • 1
  • 24
  • 16