Jump to content
  • Advertisement
Sign in to follow this  
BlackLiquid

sprintf and precision

This topic is 4908 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!