Search code examples
iosobjective-cios5floating-point

Is it possible to get a float value with unknown decimal point?


I want to pass a parameter for deciding how many value should come after decimal point like below

int decimalpoint=2;
NSString *deciPnt=@".2";
NSString *deciPnts=@"2";
CGFloat floatvalue=4.256345;

NSlog(@"Req floatvalue= %%df",decimalpoint,floatvalue);
output should be: Req floatvalue= 4.25

or

NSlog(@"Req floatvalue= %%@f",deciPnt,floatvalue);
output should be: Req floatvalue= 4.25

or

NSlog(@"Req floatvalue= %%@f",deciPnts,floatvalue);
output should be: Req floatvalue= 4.25

I tried this it will not working for me.. I know it will possible by NSLog(@"Req floatvalue= %.2f",floatvalue);

Please share your ideas, I hope they will help me....


Solution

  • I've had to think about the question quite a bit... Not sure if this is what you want, but you can use the variable-precision conversion specifier, *:

    NSLog(@"%.*f", 2, 2.44793);
    

    (Note that this is POSIX and works with printf() as well.)