Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding doubles for use in NSString

I have a situation where I have lots of different double values, for example 1.00, 0.25 and 2.50. I would like to round these doubles so that they become 1, 0.25 and 2.5; in other words I want to remove any trailing 0's. Is there a way to do this?

At the moment I have been using %.2f, and I'm wondering if I can make use of this but adapt it in some way. Please can someone help me out?


2 Answers

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.

like image 145
jscs Avatar answered Nov 28 '25 01:11

jscs


I believe you want the %g format specifier to redact trailing zeros.

like image 22
Mark Adams Avatar answered Nov 28 '25 03:11

Mark Adams