2011-12-13 12 views
6

tengo el siguiente código:Objective-C stringvalue de doble

double d1 = 12.123456789; 

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

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

¿Cómo puedo obtener un valor de cadena que es exactamente la misma que d1?

Respuesta

6

¿Qué tal

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

O simplemente ir a por el doble como

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

'% d' es un número entero – PengOne

+0

@PengOne Lo arreglé para él, lo convertí en'% lf', punto flotante largo. –

+0

@ RichardJ.RossIII Mi comprensión es que '% lf' solo es necesario cuando' scan'ing. – PengOne

11

Le puede ayudar a echar un vistazo a la guía de Apple para 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 

también leer sobre floating point (in)accuracy, y, por supuesto What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Si realmente desea que la cadena coincida exactamente con la doble, utilice NSString para codificarla y llame al doubleValue cuando desee el valor. También echa un vistazo a NSNumberFormatter.

Cuestiones relacionadas