Reputation: 424
I need to format decimal numbers using NSNumberFormatter. The result needs to be as follow
7 => 7
7.1 => 7.10
so if number have decimal part show it with 2 decimals.
I've tried with maximumFractionDigits = 2 and positiveFormat = @"###0.00" but it's not giving result I'm expecting
7 => 7.00
7.1 => 7.10
What is best positiveFormat to achieve my result?
here is code I'm using
NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
numberFormatter.minimumFractionDigits = 0;
numberFormatter.maximumFractionDigits = 2;
numberFormatter.positiveFormat = @"###0.00";
My solution
if ([number doubleValue] == [number integerValue]) {
// use formatter with minimumFractionDigits = 0 and maximumFractionDigits = 0
} else {
// use formatter with minimumFractionDigits = 2 and maximumFractionDigits = 2
}
Upvotes: 3
Views: 1411
Reputation: 2629
There is no way to achieve that by setting properties of NSNumberFormatter
. You can achieve that in two ways:
First way:
subclass NSNumberFormatter
and implement it's stringFromNumber:
method (or any related that you use for formatting. Then you set manually both minimumFractionDigits
and maximumFractionDigits
before formatting, like this (pseudocode) in stringFromNumber
override, "numberHasDecimalFraction" is boolean condition you have to implement:
if(numberHasDecimalFraction){
self.minimumFractionDigits = 2;
self.maximumFractionDigits = 2;
}else{
self.minimumFractionDigits = 0;
self.maximumFractionDigits = 0;
}
return [super stringFromNumber: number];
Second way:
Create a wrapper around two formatters and use it to format falling back on one of them depending on condition of having fraction digits similar to what you have in first way.
Upvotes: 1