Search code examples
iosobjective-cnsnumberformatter

NsNumberFormatter not giving correct result


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


Solution

  • Set both

    _numberFormatter.maximumFractionDigits = 2;
    _numberFormatter.minimumFractionDigits = 2;
    

    if you always want to print two digits after the decimal separator.