Skip to main content
GameDev.net gamedev.net
🔒 Locked

sprintf and precision

Started by BlackLiquid Feb 9, 2005 at 8:26 AM 4 replies 1.4k views
Original Post
BlackLiquid
BlackLiquid
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
Wan
Wan
Using sprintf in two stages?
CHAR buffer1[255];CHAR buffer2[255];sprintf(buffer1, "\nFloating point value is: %%%d.5f", numDeci);sprintf(buffer2, buffer1, aValue);
BlackLiquid
BlackLiquid
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.
mutex
mutex
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);

BlackLiquid
BlackLiquid
Worked like a charm mutex! Thanks to both of you for the assist.
Zahlman
Zahlman
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;

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.