Why does sprintf_s give different results in different versions of Visual Studio?

sprintf_s(buf, "%.*f", 14, 0.182696884245135); 

in VS2008 = 0.18269688424514

in VS2015 = 0.18269688424513

Has the behavior for sprintf_s been changed? How can I get the old behavior?

+6
source share
2 answers

We redesigned the parser and floating point formatter for Universal CRT> and Visual C ++ 2015 to improve the correctness. See the Breaking Changes in Visual C ++ Documentation for Visual C ++ 2015; there is a section "Formatting and disassembling with a floating point".

Visual C ++ 2015 Result - The result is correctly rounded. The input string 0.182696884245135 converted to the following double-precision value, which is the nearest representable value:

 0.18269688424513'49994693288181224488653242588043212890625 

Pay attention to the mark after the 14th decimal digit. The 15th digit is 4 , so when formatting a number with 14 fractional digits, the number is "rounded up" (or truncated), not up.

The result of Visual C ++ 2008 is incorrect. I do not know if an error was introduced during parsing or formatting. Unable to get old, incorrect behavior with Universal CRT and Visual C ++ 2015.

+9
source

Vs2008 used 80 bit floating point and rounded this more accurate value when converting to double.

Vs2015 does not do this and just truncates the literal.

I believe that you can switch between two schemes by changing the compiler settings.

+1
source

All Articles