使用double和oStringStream时的奇怪行为

Odd behavior with doubles and oStringStream

本文关键字:double oStringStream 使用      更新时间:2023-10-16

所以我正在工作的表达式求值器作为一个工作相关项目的内部组件。但是当涉及到浮点数学的输出时,我有一些奇怪的行为…

求值器接受字符串

e.evaluate("99989.3 + 2346.4");
//should be 102335.7
//result is 102336
//this function is what returns the result as a string
template <class TYPE> std::string Str( const TYPE & t ) {
    //at this point t is equal to 102335.7
std::ostringstream os;
os << t;
    // at this point os.str() == 102336
return os.str();

看起来就好像任何大于e+004的浮点数都被舍入到最接近的整数。谁能解释一下为什么会发生这种情况,我该如何克服这个问题?

可以使用std::setprecision来设置精度。

使用std::fixed