# sprintf and precision

## 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 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 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 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 on other sites
Worked like a charm mutex! Thanks to both of you for the assist.

##### 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;

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627637
• Total Posts
2978336

• 10
• 12
• 22
• 13
• 33