Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber to float Value

Tags:

ios

When I convert NSNumber to float value using 'floatValue', there is a difference in precision. Example, I have a NSNumber 'myNumber' having value 2.3, and if I convert myNumber to float using 'floatValue', its value becomes, 2.29999. But I need exactly 2.30000. There is no problem with number of zeros after 2.3, I need '2.3' instead of '2.9'.

How can I do so?

like image 740
rakeshNS Avatar asked Jul 21 '26 02:07

rakeshNS


2 Answers

I had similar situation where I was reading value and assigning it back to float variable again.

My Problem statement:

 NSString *value = @"553637.90";
 NSNumber *num = @([value floatValue]); // 1. This is the problem. num is set to 553637.875000     
 NSNumberFormatter *decimalStyleFormatter = [[NSNumberFormatter alloc] init];
 [decimalStyleFormatter setMaximumFractionDigits:2];
 NSString *resultString = [decimalStyleFormatter stringFromNumber:num]; // 2. string is assigned with rounded value like 553637.88
 float originalValue = [resultString floatValue]; // 3. Hence, originalValue turns out to be 553637.88 which wrong.

Following worked for me after changing lines:

    NSNumber *num = @([value doubleValue]); // 4. doubleValue preserves value 553637.9
    double originalvalue = [resultString doubleValue]; // 5. While reading back, assign to variable of type double, in this case 'originalValue'

I hope this would be helpful. :)

like image 106
Hitesh Savaliya Avatar answered Jul 23 '26 14:07

Hitesh Savaliya


If you need exact precision, don't use float. Use a double if you need better precision. That still won't be exact. You could multiply myNumber by 10, convert to an unsigned int and perform your arithmetic on it, convert back to a float or double and divide by 10 and the end result might be more precise. If none of these are sufficiently precise, you might want to look into an arbitrary precision arithmetic library such as GNU MP Bignum.

like image 27
autistic Avatar answered Jul 23 '26 16:07

autistic