用浮萍净化漂浮物 [英] Rounding off floats with ostringstream

查看:214
本文介绍了用浮萍净化漂浮物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用ostringstream从float转换为c ++字符串的问题。这是我的行:

I have an issue regarding conversion from float to c++ string using ostringstream. Here is my line:

void doSomething(float t)
{
    ostringstream stream; 
    stream << t;
    cout << stream.str();
}

当t值为-0.89999时,它舍入到-0.9,它的值是0.0999或更小,这说明1.754e-7,它只打印没有四舍五入。

when t has value -0.89999 it is round off to -0.9, but when it's value is 0.0999 or lesser than this say 1.754e-7, it just prints without round off. what can be the solution for this.

推荐答案

您需要使用 precision

You need to set the precision for ostringstream using precision

例如

stream.precision(3);
stream<<fixed;    // for fixed point notation
//cout.precision(3); // display only
stream << t;

cout<<stream.str();

这篇关于用浮萍净化漂浮物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆