Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 812
Nithin Michael Avatar asked Nov 29 '13 09:11

Nithin Michael


People also ask

How do you turn a string into a float?

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.

What converts a string to floating point number?

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.

Which of the following method is used to convert string input to float?

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.


1 Answers

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.

like image 154
Milo Avatar answered Sep 22 '22 17:09

Milo