I need to print a float value in area of limited width most efficiently. I'm using an NSNumberFormatter
, and I set two numbers after the decimal point as the default, so that when I have a number like 234.25
it is printed as is: 234.25
. But when I have 1234.25
I want it to be printed as: 1234.3
, and 11234.25
should be printed 11234
.
I need a maximum of two digits after the point, and a maximum of five digits overall if I have digits after the point, but it also should print more than five digits if the integer part has more.
I don't see ability to limit the total number of digits in NSNumberFormatter
. Does this mean that I should write my own function to format numbers in this way? If so, then what is the correct way of getting the count of digits in the integer and fractional parts of a number? I would also prefer working with CGFLoat
, rather than NSNumber
to avoid extra type conversions.
Best Answer
You're looking for a combination of "maximum significant digits" and "maximum fraction digits", along with particular rounding behavior.
NSNumberFormatter
is equal to the task:Result: