简体   繁体   中英

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....

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM