Reputation: 429
I am facing an issue but couldn't seem to find a solution.I have a textfield where user is entering numbers.The issue is that when the user enters last digit as zero after decimal place,it is not taking.e.g. - 42.70 is printed as 42.7.Find the code below
NSNumberFormatter *_numberFormatter =[NSNumberFormatter new];
_numberFormatter.maximumFractionDigits=2;
_numberFormatter.minimumIntegerDigits=1;
_numberFormatter.roundingMode=kCFNumberFormatterRoundCeiling;
_numberFormatter.allowsFloats=YES;
_numberFormatter.groupingSeparator=@",";
_numberFormatter.usesGroupingSeparator=YES;
_numberFormatter.groupingSize=3;
_numberFormatter.minimum=[NSNumber numberWithInt:0];
[_numberFormatter setLenient:YES];
[_numberFormatter setUsesSignificantDigits:NO];
and
NSNumber *number = [nf numberFromString:combinedString];
NSString *formattedString = [nf stringFromNumber:number];
formatted string is printing the value entered sans 0 if entered in last place but it prints the correct number if any other digit is there like 42.78 is printed as it is but 43.70 is printed as 43.7.
Am i missing setting some parameters.Any help is needed
Thanks in Advance
Upvotes: 0
Views: 282
Reputation: 429
Found out that we have to do manipulations to add a zero from our side.iOS works in a weird way and doesn't allow it.So below is my code.Hope it is helpful for others also.
NSArray *formatArr = [combinedString componentsSeparatedByString:@"."];
NSString *str = [formatArr lastObject];
NSString *code;
if ([str length] >0) {
code = [[formatArr lastObject] substringFromIndex: [str length] - 1];
if ([str isEqualToString:@"00"])
{
}
else
{
if ([combinedString hasSuffix:@".0"])
{
formattedString=[formattedString stringByAppendingString:@".0"];
}
else if ([code isEqualToString:@"0"]) {
formattedString = [formattedString stringByAppendingString:@"0"];
}
}
}
else
{
if ([combinedString hasSuffix:@".0"])
{
formattedString=[formattedString stringByAppendingString:@".0"];
}
}
Combinedstring is the input user is entering.I am checking for the '.' place and checking if the last digit is zero.If it is,then adding a zero from my own.Now user is able to see 43.50 when he types it instead of 43.5
Upvotes: 0
Reputation: 540055
Set both
_numberFormatter.maximumFractionDigits = 2;
_numberFormatter.minimumFractionDigits = 2;
if you always want to print two digits after the decimal separator.
Upvotes: 2
Reputation: 7123
You can use this:
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:@"0.##"];
NSNumber *n = [NSNumber numberWithFloat:47.78];
NSLog(@"%@", [fmt stringFromNumber:n]);
it will print 47.78
Upvotes: 0