user843337
user843337

Reputation:

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?

Upvotes: 2

Views: 807

Answers (4)

Ankit Srivastava
Ankit Srivastava

Reputation: 12405

Here is a list of all the format specifiers that you can use...

%@     Object
%d, %i signed int
%u     unsigned int
%f     float/double

%x, %X hexadecimal int
%o     octal int
%zu    size_t
%p     pointer
%e     float/double (in scientific notation)
%g     float/double (as %f or %e, depending on value)
%s     C string (bytes)
%S     C string (unichar)
%.*s   Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second)
%c     character
%C     unichar

%lld   long long
%llu   unsigned long long
%Lf    long double

Upvotes: 1

Mark Adams
Mark Adams

Reputation: 30846

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

Upvotes: 2

Littlejon
Littlejon

Reputation: 1066

Not really rounding, but have you tried just %f it should only show the number of digits required rather then padding out the number.

My answer above is wrong, %g as others has stated is the right way to go.

The documentation for string formatters should help too. http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265

Upvotes: 1

jscs
jscs

Reputation: 64002

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.

Upvotes: 12

Related Questions