Correct behavior for std :: setprecision (0) in GCC vs VS2013

Depending on which compiler I use, I get excellent output for this function with n = 0.

std::string ToStrWPrec(double a_value, const int n)
{
    std::ostringstream out; 
    out << std::setprecision(n) << a_value; 
    return out.str();
}

(GCC) 4.8.3 20140911 (Red Hat 4.8.3-9) returns 1 for ToStrWPrec (1.2345678,0). VS2013 returns 1.2346 for the same code.

my question is:

  • What is the correct / standard behavior for setprecision?
  • What would be a good alternative to using setprecision?

here is the updated code based on the comment below

std::string ToStrWPrec(double a_value, const int n)
{
    std::ostringstream out; 
    out << std::setprecision(n) << std::fixed<< a_value; 
    return out.str();
}
+4
source share
1 answer

In accordance with paragraph 22.4.2.2.2 [facet.num.put.virtuals] of paragraph 5, step 1, this indicates accuracy:

, floatfield != (ios_base::fixed | ios_base::scientific), str.precision() . .

, , , %g.

floatfield 27.5.5.2 [basic.ios.cons], 128:

flags() skipws | dec

, , "%.0g" . C 7.21.6.1 8 :

P , , 6, , 1, .

, 1.

+2

Source: https://habr.com/ru/post/1623001/


All Articles