How do I achieve the following conversion from double to a string:
1.4324 => "1.43"
9.4000 => "9.4"
43.000 => "43"
i.e. I want to round to to decimal places but dont want any trailing zeros, ie i dont want
9.4 => "9.40" (wrong)
43.000 => "43.00" (wrong)
So this code which I have now doesn't work as it displays excess zeros:
[NSString stringWithFormat: @"%.2f", total]
Use NSNumberFormatter. See the Data Formatting Programming Guide's chapter on Number Formatters.
The easiest way is to probably roll your own. I've had to do this in C before since there's no way to get the behavior you want with
printf
formatting.It doesn't appear to be much easier in Objective-C either. I'd give this a try:
or this (possibly faster) variant:
The
stringWithFormat
guarantees there will always be a".nn"
at the end (wheren
is a digit character). Thewhile
andif
simply strip off trailing zeros and the trailing decimal if it was an integer.Obviously, you may want to put it in a function or class so you can get at it from anywhere without having to duplicate the code all over the place.
I am pretty sure that [[NSNumber numberWithFloat:f] stringValue] does exactly what you want.
You made simple mistake. This will work:
I'm not familiar with objective C, but this isn't possible with standard printf-style formatting.
Using %g would sort-of work, but for large or small numbers it would use scientific notation (eg 9.6e+6, 4.2e-7) rather than decimal notation.
The equivalent question was asked for C/C++ here, and in that case the answer is to use %f and then strip any trailing 0's from the string. Not exactly elegant.