My NSString value is 28.4701278 after converting into double I want same value as 28.4701278
Asked
Active
Viewed 85 times
2
-
what are u getting then? and what did u try ? – iAnurag Feb 02 '16 at 10:11
-
After converting into double, I want same value in double as 28.4701278 – Nazish Ali Feb 02 '16 at 10:12
-
It's just a floating point rounding error. – trojanfoe Feb 02 '16 at 10:33
4 Answers
3
IEEE 754 floating-point number (used in double
) cannot accurately represent every single decimal number. See: Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?
If loss of significance is not acceptable, use NSDecimalNumber
instead of double
.

Siyu Song
- 897
- 6
- 21
1
NSString *stringValue = @"28.4701278";
double doubleValue = [stringValue doubleValue];

Madan gupta
- 668
- 6
- 19
-
NSString *stringValue = @"28.4701273"; double doubleValue = [stringValue doubleValue]; the out put will be : 28.470127300000001 – Nazish Ali Feb 02 '16 at 10:15
-
-
in my case output is same as above... can share your code where you are using it? – Madan gupta Feb 02 '16 at 10:18
-
-
i think you only need double data structure while performing some mathematical operation and for tht 28.470127300000001 is almost equal to 28.4701273. and if you want to display it anywhere than you can again convert it to string and it will be 28.4701273. for conversion from double to string you can use NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init]; [fmt setPositiveFormat:@"0.#######"]; NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithDouble:doubleValue]]); – Madan gupta Feb 02 '16 at 10:38
1
simple try
double finalValue = [@"28.4701278" doubleValue];
NSLog(@"final value ==%f",finalValue);
you get output like
Update
double finalValue = [@"28.4701273" doubleValue];
NSLog(@"final value ==%f",finalValue);
I get output like
Edit
use NSDecimalNumber
instead of double
NSDecimalNumber *decimalNum= [NSDecimalNumber decimalNumberWithString:@"28.4701273"];
NSLog(@"final ==%@",decimalNum);
output is

Anbu.Karthik
- 82,064
- 23
- 174
- 143