Reputation: 1490
I’m using NSNumberFormatter
to format an NSDecimalNumber
.
What configuration can I use to display the number 0.012676
as 1
?
Important: I am not trying to round up to 1.0 — I’m trying to round to the hundred place in the decimal, and then strip the preceding zeros and decimal separator.
My current configuration looks something like this:
// in a method...
NSDecimalNumber *value = /* retrieve a value like 0.012676 */;
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
// this is the rounding behavior I want
[nf setRoundingMode: NSNumberFormatterRoundHalfEven];
[nf setMinimumFractionDigits: 2];
[nf setMaximumFractionDigits: 2];
return [nf stringFromNumber: value];
which generates an output of:
.01
With thanks to dasblinkenlight and Twitter friends, the solution is simply to multiply by 100
, and then eliminate the fraction digits:
[nf setMultiplier: [NSNumber numberWithInt: 100]];
[nf setMinimumFractionDigits: 0];
[nf setMaximumFractionDigits: 0];
Upvotes: 2
Views: 455
Reputation: 726489
You can eliminate N
leading zeros by multiplying by the N
-th power of ten. Since you are looking for the hundredth place, multiply 0.012676
by 100
, and convert it to an integer.
Upvotes: 2