2011-12-13 12 views
6

Ho il seguente codice:Objective-C stringvalue dalla doppia

double d1 = 12.123456789; 

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

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

Come faccio ad avere un valore di stringa che è esattamente lo stesso di d1?

risposta

6

Come su

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

O semplicemente per il doppio come

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

'% d' è un numero intero – PengOne

+0

@PengOne L'ho corretto per lui, convertito in'% lf', lungo punto mobile. –

+0

@ RichardJ.RossIII La mia comprensione è che '% lf' è necessario solo quando' scan'ing. – PengOne

11

Essa può aiutare a dare un'occhiata a guida di Apple per 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 

Leggi anche su floating point (in)accuracy, e, naturalmente What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Se si desidera che la stringa corrisponda esattamente al doppio, utilizzare NSString per codificarlo e chiamare doubleValue quando si desidera il valore. Dai un'occhiata anche allo NSNumberFormatter.