Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone NSString stringWithFormat and float

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?

like image 507
Valentin Stoianoff Avatar asked Dec 22 '22 02:12

Valentin Stoianoff


2 Answers

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];
like image 111
Magic Bullet Dave Avatar answered Jan 13 '23 14:01

Magic Bullet Dave


Not sure if this is what you want but try something like the following:

NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
// set to long number of decimals to accommodate whatever a user might enter
[nf setMaximumFractionDigits:20]; 
NSString *s = [nf stringFromNumber:
               [NSNumber numberWithDouble:[userEnteredNumberString doubleValue]]
               ];
NSLog(@"final:%@",s);
like image 31
ragamufin Avatar answered Jan 13 '23 12:01

ragamufin