Search code examples
iosnsnumberformatter

Showing a string as number with two decimal places


In my iOS app, I am receiving JSON data from a remote server. One of the fields value can be a double number, like 24.87,or an int number, like 24. Now I want to show the number in a view, as label text, but I want always to get a 2 decimal places number, as example if the remote value is 24, I want to show 24.00...

I am using the following code to do it:

if ([tarifa_comanda isEqualToString:@"T1"]){
        cell.tarifa_label.text = @"T1";

        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        [f setNumberStyle:NSNumberFormatterDecimalStyle];
        NSNumber * myNumber = [f numberFromString:[[categorias objectAtIndex:indexPath.row] objectForKey:@"precio1_plato"]];
        cell.precio_plato_label.text = myNumber;  

    }

But I am getting a wrong output from the number. This is what I am getting, the label is the one with the blue background:

enter image description here


Solution

  • You can set the maximum and minimum number of fraction digits that you want your formatter to display by setting its maximumFractionDigits and minimumFractionDigits properties.

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setMaximumFractionDigits:2];
    [formatter setMinimumFractionDigits:2];
    
    NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:25.342]]);
    NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:25.3]]);
    NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:25.0]]);