Ad

Our DNA is written in Swift
Jump

Variable Number of Decimal Places

Trapper asks:

I have one integer holding a variable number of decimal places that another variable needs to be rounded to when I stringWithFormat it. What is the correct way to do this?

Trapper is not content with just specifying %.2f in a stringWithFormat, but he wants the number of decimal places to be dependent on a second variable.

Here is the shortest method I came up with.

int decimals = 3;
double d = 3.1415;
   
NSString *format = [NSString stringWithFormat:@"%%%0.1ff", decimals/10.0];
NSString *formattedString = [NSString stringWithFormat:format, d]; // e.g. %0.3f 
NSLog(formattedString);

I got confused at first because the NSLog would always output a strange value when wanted to output the formatting string. Then I remembered that the first parameter of NSLog itself is also interpreting formatting information. NSLog combines stringWithFormat into the output.

That’s good to know in case you want to add an NSLog statement for debugging floating point variables.

double d = 3.1415;
NSLog("%0.2f", d);  // formatting directly here

Categories: Q&A

0 COmments »

  1. also check setPositiveFormat
    http://tinyurl.com/dhxgft

    Laurent