1

I am using the following statement to get a float value from table:

NSNumber *f = [NSNumber numberWithDouble:(double)sqlite3_column_double(statement, 0)];

The value in the database is 23.679999999 but I am getting 23.68. I tried numberWithFloat but i got the same result. Can anyone tell me how to get the value without rounding off?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109

1 Answers1

1

NSNumber-wrapped-double is not a suitable data type for storing decimal values when all digits must be preserved exactly. Use NSDecimalNumber instead:

unsigned char *c = sqlite3_column_text(statement, 0);
NSNumber *f = nil;
if (c) {
    NSString *numStr = [NSString stringWithUTF8String:c];
    f = [NSDecimalNumber decimalNumberWithString:numStr];
}

This should preserve all significant digits available in your text representation, as long as you use the native value. Converting to float or double may result in rounding due to differences in representation.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523