To convert a number value using grouping and decimal separator according to your desired locale you definitely need to use NSNumberFormatter
.
On an instance of NSNumberFormatter
you can set your desired rounding algorithm (number of digits, rounding behavior). Also it will automatically use current locale for you. You'll be left with a simple
[numberFormatter stringFromNumber:myNumber];
Note that you'll be able to use different formatters that have different rounding rules: 2/3
can be printed as 0.6
, 0.7
, 0.67
and so on. If your number is inherently decimal, like the numbers that occur in finance, you can consider using NSDecimalNumber
to hold the number value. Once set, an instance of NSDecimalNumber
will remember the exact number of decimal digits and if you print it with a generic NSNumberFormatter
, you'll never lose significant digits.
This is how you can limit the total number of digits to 10:
- Given a decimal number, divide or multiply it by 10 until it's between 0.1 and 1.
- Round it to 10 digits after decimal point.
- Reverse the procedure in 1.
- Now you have a decimal number with exactly 10 significant digits.
Technically, you're able to convert NSDecimalNumber
to a string without using an NSNumberFormatter
by -descriptionWithLocale:
. But I don't think it can do groupings.
And if your code isn't supposed to be internationalized, you can also do
[NSString stringWithFormat:@"%@", decimalNumber];