objective c - How to restrict number of fraction digits when parsing number from string? -


i want restrict number of fraction digits user allowed enter uitextfield accepts (localized) numeric input.

example 4 fraction digits allowed:

  • good: 42, 10.123, 12345.2345
  • bad: 0.123456, 6.54321

right now, i'm using nsnumberformatter's numberfromstring: in uitextfield delegate's textfield:shouldchangecharactersinrange:replacementstring: determine whether it's legal numeric value.

unfortunately, nsnumberformatter seems ignore maximumfractiondigits in numberfromstring:. in tests using getobjectvalue:forstring:range:error: had same problem, , range full length of string afterwards (unless start entering letters; range indicates part of string digits):

nsnumberformatter* formatter = [[nsnumberformatter alloc] init]; formatter.maximumfractiondigits = 3; formatter.roundingmode = nsnumberformatterroundhalfup; formatter.generatesdecimalnumbers = yes; nsdecimalnumber* n = (nsdecimalnumber*)[formatter numberfromstring:@"10.12345"]; nslog(@"number: %@", n.description); // expected: 10.123, is: 10.12345 

how best restrict number of fraction digits in user input?

after unrestricted number, can use stringwithformat on number create string number of decimal places.

eg.

double number = mytextfield.text.doublevalue; nsstring *restrictedstring =  [nsstring stringwithformat:@"%.4f", number]; 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -