2

My NSString value is 28.4701278 after converting into double I want same value as 28.4701278

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Nazish Ali
  • 320
  • 3
  • 16

4 Answers4

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
  • Not same 28.4701273 – Nazish Ali Feb 02 '16 at 10:16
  • 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
  • Please show your out put console. – Nazish Ali Feb 02 '16 at 10:29
  • 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

enter image description here

Update

 double finalValue = [@"28.4701273" doubleValue];
 NSLog(@"final value ==%f",finalValue);

I get output like

enter image description here

Edit

use NSDecimalNumber instead of double

 NSDecimalNumber *decimalNum= [NSDecimalNumber decimalNumberWithString:@"28.4701273"];
NSLog(@"final  ==%@",decimalNum);

output is

enter image description here

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
1

Try this:

var string = "28.4701278"
var a = Double(string)

Output

iAnurag
  • 9,286
  • 3
  • 31
  • 48