Sign in to follow this  

sprintf and precision

This topic is 4692 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've been having a little trouble setting the precision of float values with sprintf. I have a variable numDeci which holds the precision the user wants. This is what I'm using now as a default: sprintf(buffer, "Floating point value is: %.5f", aValue); My question is this: How can I set the precision using my "numDeci" variable? I've tried a few variants like %.(numDeci)f but nothing has worked so far :P

Share this post


Link to post
Share on other sites
Using sprintf in two stages?

CHAR buffer1[255];
CHAR buffer2[255];

sprintf(buffer1, "\nFloating point value is: %%%d.5f", numDeci);
sprintf(buffer2, buffer1, aValue);

Share this post


Link to post
Share on other sites
Thanks for the reply. I think I see where you're going with that example,
but won't it still print a float value with 5 decimals? I want that number to
be user defined. I'll give your code a whirl when I get back to my workstation.

Share this post


Link to post
Share on other sites
According to this, you can replace the precision with an asterisk, and add a corresponding int specifying the precision to the argument list:


int prec = 5;
sprintf(buffer, "Floating point value is: %.*f", prec, aValue);

Share this post


Link to post
Share on other sites
No thread of this sort is complete without a plug for the C++ Way (TM):

stringstream buffer;
// ...
buffer.precision(prec);
buffer << "Floating point value is: " << aValue;

Share this post


Link to post
Share on other sites

This topic is 4692 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this