¿Convertir de NSString a flotar?

How can I convert this number to a float? It is 35.77091272818393, type NSString. The problem is that, if I use

[str doubValue]

devuelve 35.770912.


Quiero convertir esta cadena

NSString *tt =[NSString stringWithFormat:@"%.14f", 35.77091272818393 ];

to a float using

var=[tt floatValue];

but it does not have enough precision - it only returns 35.7709127 and not all the digits.

preguntado el 09 de marzo de 12 a las 16:03

1 Respuestas

Your problem is that the value 35.770912 you are seeing is the rounded double-precision floating point value. If you want more decimal points, than you can use something like the following:

[NSString stringWithFormat:@"%.14", @"35.77091272818393"];

This will print out the value with 14 decimal points, and you will see that the precision has not been lost in the floating point value.


You are having problems with the second part of your question because you're accessing the floatValue property of the string instead of the doubleValue property. The number you reference requires more precision than float provides. You must store the number in a double-precision floating-point type. Something like this should fix your problem:

NSString *tt = [NSString stringWithFormat:@"%.14f", 35.77091272818393];
double var = [tt doubleValue];

respondido 12 mar '12, 12:03

my problem is, i want to affect this resultat NSString *tt =[NSString stringWithFormat:@"%.14f", 35.77091272818393 ]; to var=[tt floatValue]; but i have problem about precision beacause return to me only 35.7709127 and not all number - B.Moahmmed.Amine

I added additional details to my answer to address your clarification. - steven oxley

Two days I was looking at this issue until I found this post. The above solution worked. - Jeremy

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.