Alice Turner
Alice Turner

Reputation: 87

Float precision not formatting in string

When I write a simple wprintf function and pass a double to it a float number using the verb notation L"%.2f" it simply prints an "f" on the screen instead of a number like in the format 0.00.

I would like some help as everywhere I look it simply says L"%.2f" is the way to print a number with 2 decimal digit precision.

float duration = (float)((std::clock() - mTimer) / (float)(CLOCKS_PER_SEC / 1000));
wsprintf(message, L">> Speed: %.2f\r\n", duration);

These are the 2 lines causing my headache... they result in

>> Speed: f

being printed on the console.

The output i'm looking for is this:

>> Speed: 4000.00

Upvotes: 2

Views: 355

Answers (2)

P.W
P.W

Reputation: 26800

The function wsprintf() (which seems to be windows specific) does not support floating point parameters, You can go for swprintf() (which is a standard library function) instead.

Moreover, there is a note in the wsprintf documentation which states:

Do not use. Consider using one of the following functions instead: StringCbPrintf, StringCbPrintfEx, StringCchPrintf, or StringCchPrintfEx. See Security Considerations.

Upvotes: 5

Can Oezlemis
Can Oezlemis

Reputation: 212

What you can do is :

cout << fixed << setprecision(2) << message << ">> Speed : "<< duration << endl;

Upvotes: 0

Related Questions