实战c++中的string系列--指定浮点数有效数字并转为string

上一篇博客讲了好几种方法进行number到string的转换,这里再单独说一下float或是double到string的转换。

还是处于控件显示的原因,比如说要显示文件的大小,我们从服务器可以获得这个文件的总bytes。这样就需要我们根据实际情况是显示bytes、kb、mb等单位。

常用的做法就是把num_bytes/1024,这个时候往往会得到浮点型,浮点型转string也没问题,但是如果你需要保留这个浮点型的一位或是几位小数,怎么操作会方便快捷呢?

你进行了相关搜索,但是很多人给你的回答都是要么使用cout, 要么使用printf进行格式化输出。

我们使用的是stringstream

Stringstreams allow manipulators and locales to customize the result of these operations so you can easily change the format of the resulting string

#include <iomanip>
#include <locale>
#include <sstream>
#include <string> // this should be already included in <sstream>

// Defining own numeric facet:
class WithComma: public numpunct<char> // class for decimal numbers using comma instead of point
{
    protected:
        char do_decimal_point() const { return ','; } // change the decimal separator
};

// Conversion code:

double Number = 0.12;           // Number to convert to string

ostringstream Convert;

locale MyLocale(  locale(), new WithComma);// Crate customized locale

Convert.imbue(MyLocale);       // Imbue the custom locale to the stringstream

Convert << fixed << setprecision(3) << Number; // Use some manipulators

string Result = Convert.str(); // Give the result to the string

// Result is now equal to "0,120"

setprecision
控制输出流显示浮点数的有效数字个数 ,如果和fixed合用的话,可以控制小数点右面的位数
但是这里需要注意的是头文件:

#include <iomanip>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值