Parv Bhasker
Parv Bhasker

Reputation: 1901

format the decimal number using NSNumberFormatter

hello i am in a need to format the decimal number entered by user in the app like.

100.  = 100
90.00  = 90
90.1  = 90.1
90.22 = 90.22
90.227 = 90.23

how should i achieve this using NSNumberFormatter.

i achieved the same using this custom if else condition

if ([cell.textField.text rangeOfString:@"."].location != NSNotFound)
    {
        NSString *strAfterDecimal = [cell.textField.text componentsSeparatedByString:@"."].lastObject;
        NSInteger count = [strAfterDecimal length];

        if(count == 0)
        {
            customField.value = [cell.textField.text
                                 stringByReplacingOccurrencesOfString:@"." withString:@""];
        }
        else if(count == 1 || count == 2)
        {
            if([strAfterDecimal integerValue] > 0)
            {
                customField.value = cell.textField.text;
            }
            else
            {
                customField.value = [cell.textField.text componentsSeparatedByString:@"."].firstObject;
            }
        }
        else if(count > 2)
        {
            if([strAfterDecimal integerValue] > 0)
            {
                customField.value = [NSString stringWithFormat:@"%0.2f",[cell.textField.text floatValue]];
            }
            else
            {
                customField.value = [cell.textField.text componentsSeparatedByString:@"."].firstObject;
            }
        }
    }

I need to consize the code. As according to client i cant put extra code if default functions given by apple do the things

Upvotes: 1

Views: 468

Answers (1)

vadian
vadian

Reputation: 285220

It's very straightforward

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSNumber *number = [formatter numberFromString:cell.textField.text];
NSString *numberString =  [formatter stringFromNumber:number];
if (numberString == nil) numberString = @"0";
NSLog(@"%@", numberString);

The Swift version is a bit more complicated because you have to safely unwrap the optionals

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
let numberString : String
if let text = cell.textField.text,
    let number = formatter.number(from: text),
    let string = formatter.string(from: number) {
    numberString =  string
} else {
    numberString = "0"
}
print(numberString)

Upvotes: 3

Related Questions