Iphone NSString stringWithFormat and float

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

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

But this gives me a lot of extra digits after the period (for example, for 2.25 it gives 2.249999).

All I need to do is filter the input file so that it is a legitimate float (numbers and not more than one dot).

How to do it?

+4
source share
3 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 can use string manipulation to determine the number of decimal places the user entered (remember to check for cases of edges):

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

and then, if you want to create a new line with a new float with the same level of display accuracy, you can use:

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

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); 
+1
source

Try using double instead of float. I think double removes all trailing zero.

-one
source

Source: https://habr.com/ru/post/1394556/


All Articles