LS_
LS_

Reputation: 7129

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];

Upvotes: 1

Views: 618

Answers (4)

Volker
Volker

Reputation: 4660

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.

Upvotes: 4

zaph
zaph

Reputation: 112857

Any trailing zeros are simple a display issue, they are no part of the number.

Upvotes: 1

peig
peig

Reputation: 418

You can't, the thing that you have to do if you want to show the numbers with two decimals after saving them as a NSNumber is print them as a float with two decimals. Something like that:

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

NSString *numberString = [NSString stringWithFormat:@"%0.2f", numPrice.floatValue];

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

You can't. When a JSON document contains 10.50, it is the number 10.5. There is no difference between 10.5000000 or 10.50 or 10.5 in a JSON document. They are absolutely one hundred percent the same thing.

You can feel free to display this number any way you like.

Upvotes: 0

Related Questions