Convert a string to float in Objective C without rounding it.?
How can i convert a string to float in Objective C without rounding it.?
I tried to convert a string 8.56021285234;
float result=[string floatValue];
giving 8.560213, the rounded value.
How can i avoid this? How i can get the exact value?
The problem is you're using a float. A float can usually only hold around 7-digits max. A double can hold many more digits. A float is 32-bit while a double is 64-bit therefore giving it "double" the precision. A simple work-around to your problem would be to do:
double result = [string doubleValue];
When logging, make sure to use NSLog(@"%.12f",result);
to show the entire double as %f defaults to only a 6 decimal precision.
You can't put more than about 7 digits of precision in a float. You need a type with more precision, like double, see here:
Difference between float and double
If you want to convert it use
double result = [string doubleValue];
For displaying it use %.10f to specify decimal places:
NSLog(@"%.10f", result);
链接地址: http://www.djcxy.com/p/78626.html