[英]C++ stod rounding the doubles
In c++, std::stod( string ) converts a string to a floating decimals.在 c++ 中,std::stod( string ) 将字符串转换为浮点数。 So, doing this所以,这样做
std::cout << std::stod("378760.58") << "\n"; std::cout << std::stod("378760.58") << "\n";
I would expect it to print 378760.58
to stdout but it rounds up and prints 378761
instead.我希望它将378760.58
打印到标准输出,但它四舍五入并打印378761
。 std::stod() sometimes works as expected but it sometimes acts weird in an unexpected way. std::stod() 有时会按预期工作,但有时会以意想不到的方式表现得很奇怪。
Can anyone explain why and what alternative I could use to convert from string to double in c++?谁能解释为什么以及我可以使用什么替代方法在 c++ 中将字符串转换为双精度? thanks for all the responses:)感谢所有回复:)
you can add "iomanip" head file and use the following code:您可以添加“iomanip”头文件并使用以下代码:
std::cout << std::fixed << std::setprecision(2) << std::stod("378760.58") << "\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.