Search code examples
objective-cnsnumberformatter

Convert double to NSNumber keeping decimal part even if there are 0s


I download some Json data that has inside it a price, the price gets downloaded as double so for example if I have 10.50 the value assigned to my variable will be 10.5, how can I keep the 0 after the first decimal number?

This is the code I used to create the NSNumber:

NSNumber *numPrice = jsonElement[@"Price"];  //the json is 10.50 but numPrice becomes 10.5

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *numberString = [formatter stringFromNumber:numPrice];

Solution

  • For output purposes you can set your NSNumberFormatterto have exactly 2 decimal digits like

    [formatter setMinimumFractionDigits:2];
    [formatter setMaximumFractionDigits:2];
    

    This is for displaying two decimal numbers. Internally your NSNumber will be stored of course with a single digit, if possible.