As long as you're talking only about display, this is quite easy. The format specifier you want is %g
:
The double argument shall be converted in the style f
or e
(or in the style F
or E
in the case of a G
conversion specifier), with the precision specifying the number of significant digits [...] Trailing zeros shall be removed from the fractional portion of the result[...]
double twopointfive = 2.500;
double onepointzero = 1.0;
double pointtwofive = .25000000000;
NSLog(@"%g %f", twopointfive, twopointfive);
NSLog(@"%g %f", onepointzero, onepointzero);
NSLog(@"%g %f", pointtwofive, pointtwofive);
2011-12-06 21:27:59.180 TrailingZeroes[39506:903] 2.5 2.500000
2011-12-06 21:27:59.184 TrailingZeroes[39506:903] 1 1.000000
2011-12-06 21:27:59.185 TrailingZeroes[39506:903] 0.25 0.250000
The same format specifier can be used with an NSNumberFormatter
, which will also give you some control over significant digits.
The trailing zeroes can't be removed from the way the number is stored in memory, of course.