Is there a way to prevent stringWithFormat from rounding?
I'm trying to get a string from a double like this:
double aDouble;
NSString* doubleString = [NSString stri开发者_运维技巧ngWithFormat:@"%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
%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:
- If a non-zero precision has been specified, let P be that precision
- If a zero precision has been specified, let P be 1
- If a precision hasn’t been specified, let P be 6
- Let X be the exponent if the conversion were to use the
%e
format specifier- If P > X >= -4, the conversion is with style
%f
and precision P - (X + 1) - Otherwise, the conversion is with style
%e
and precision P - 1.
- If P > X >= -4, the conversion is with style
- Unless the
#
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.
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.
精彩评论