iphone NSString stringWithFormat and float

Valentin Stoianoff picture Valentin Stoianoff · Feb 3, 2012 · Viewed 9.8k times · Source

I have an input with UIKeyboardTypeDecimalPad and I need my user to input a float (with unlimited characters after a dot). After the input I filter the string with :

NSString *newValue = [NSString stringWithFormat:@"%.f",[textField.text floatValue]]

But that gives me a lot of unnecessary digits after a dot (for example for 2.25 it gives 2.249999).

All I need is to filter the input so it'll be a legal float (digits and not more than one dot).

How do I do that?

Answer

Magic Bullet Dave picture Magic Bullet Dave · Feb 3, 2012
NSString *newValue = [NSString stringWithFormat:@"%0.1f", [textField.text floatValue]];

the number after the dot is the number of decimal places you want.

UPDATE: You could use string manipulation to determine the number of decimal places the user typed in (don't forget to check for edge cases):

NSInteger numberOfDecimalPlaces = textString.length - [textString rangeOfString:@"."].location - 1;

and then if you want to create a new string with a new float to the same level of display precision you could use:

NSString *stringFormat = [NSString stringWithFormat:@"%%0.%if", numberOfDecimalPlaces];
NSString *newString = [NSString stringWithFormat:stringFormat, newFloat];