Objective-c stringvalue of double

I have the following code:

double d1 = 12.123456789012345; NSString *test1 = [NSString stringWithFormat:@"%f", d1]; // string is: 12.123457 NSString *test1 = [NSString stringWithFormat:@"%g", d1]; // string is: 12.1235 

How to get a string value that is exactly the same as d1?

+6
source share
2 answers

This may help you take a look at Apple's guide to String format specifiers .

 %f 64-bit floating-point number %g 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise 

Also read floating point precision (in) and, of course, what every computer scientist needs to know about floating point arithmetic .

If you really want the string to match the double exactly, use NSString to encode it and call doubleValue when you want this value. Also take a look at NSNumberFormatter .

+11
source

What about

 NSString *test1 = [NSString stringWithFormat:@"%.15f", d1]; 

Or just go double as

 NSString *test1 = [NSString stringWithFormat:@"%lf", d1]; 
+6
source

Source: https://habr.com/ru/post/903710/


All Articles