Reputation: 600
Hi I want to smart round a float number, to keep the number of digits constant. This number will always have 1 or 2 integer digits + undefined decimal digits.
I want to have a number with always 3 digits regardless of their position
EX:
83.235 = 83.2
0.110321 = 0.11
4.56723 = 4.57
Upvotes: 2
Views: 102
Reputation: 7096
If leading zeroes don't count as digits
NSNumberFormatter has usesSignificantDigits, minimumSignificantDigits, and maximumSignificantDigits properties that should do what you need. Set both values to 3, or just the max if you don't want trailing zeroes on values with fewer decimal places.
If you want leading zeroes to count as digits
I'm not aware of any built-in way of handling this, but you could write some custom logic to do it. e.g.
if (yourNum < 10)
formattedNum = [NSString stringWithFormat:@"%.2f", yourNum];
else
formattedNum = [NSString stringWithFormat:@"%.1f", yourNum];
This is assuming the number is always between 0 and 99.whatever, so if you're not 100% confident in the data integrity you'll probably want some more checks.
Upvotes: 2