iPhone - Store float in SQLite thru CoreData
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
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.
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:
- A Cocoa is my girlfriend post (this might fit your situation exactly)
- A cocoa with love post
- A tutorial about the different cocoa number containers
- A stackoverflow answer
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.
精彩评论