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?
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.
The simplest way to do so is using parseFloat() method of Float class in java. lang package. This method takes the string to be parsed and returns the float type from it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With