Reputation: 51
I'm trying to get a string from a double like this:
double aDouble;
NSString* doubleString = [NSString stringWithFormat:@"%g", aDouble];
With most numbers I get the desired results, but for
10000.03
I get:
10000
as my string. Is there a way to prevent this behavior? I would like a result a string of
10000.03
Upvotes: 5
Views: 1813
Reputation:
%g
can be tricky in the absence of a precision specifier. Note that %f
can be used with double
values, and you can limit the number of digits after the decimal point by using %.2f
(replace 2
with whichever number of digits you want).
%g
is a format specifier that chooses between %f
or %e
according to the following algorithm:
%e
format specifier
%f
and precision P - (X + 1)%e
and precision P - 1.#
flag is used, any trailing zeros are removed from the fractional portion of the result, and the decimal point character is removed if there is no fractional portion remaining.In your case, %g
doesn’t specify a precision, hence P = 6. When converting 10000.03 with %e
, which gives 1.000003e+04, the exponent is 4, hence X = 4. Since P > X >= -4, the conversion is with style %f
and precision P - (X + 1) = 6 - (4 + 1) = 1. But 10000.03 with precision 1 (one digit after the decimal point) yields 10000.0, which has no actual fractional portion, hence %g
formats 10000.03 as 10000.
Upvotes: 3
Reputation: 6037
Try %.2f instead of %g
floats and double are base two representations of number that we like to see in base ten, just as there is no way to exactly represent the number 1/3 in base ten with a finite number of digits there are many base 10 number which can not be exactly represented in base 2. For example 0.1 (1/10) can not be represented exactly in base 2.
Upvotes: 1