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

还是处于控件显示的原因。比方说要显示文件的大小,我们从server能够获得这个文件的总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>

最新文章

  1. 格式化input输入内容(金额)
  2. Atitit &#160;ocr识别原理 与概论 attilax总结
  3. JavaScript原型链和instanceof运算符的暧昧关系
  4. iOS 使用封装的NSLog来打印调试信息
  5. Java Web目录
  6. General Palindromic Number (进制)
  7. linux中ctime,mtime,atime的区别
  8. [转]强大的vim配置文件,让编程更随意
  9. bzoj 1305: [CQOI2009]dance 二分+網絡流判定
  10. linux 之 yum 介绍 &lt;转&gt;
  11. BZOJ3144 切糕
  12. javascript函数的基础功能
  13. JavaSE学习总结第14天_API常用对象4
  14. oracle_oracle中修改日期的显示格式
  15. Kubernetes 使用私服镜像
  16. 树莓派3b+_32位linux系统arm架构安装JDK
  17. ActiveMQ中Broker的应用与启动方式
  18. JS实现页面字体繁简转换
  19. 2015年第六届蓝桥杯C/C++程序设计本科B组决赛 完美正方形
  20. fastclick select 闪退 bug

热门文章

  1. js hover 下拉框
  2. luogu P1238 走迷宫--DFS模板好(水)题
  3. bzoj2402 陶陶的难题II
  4. &lt;Jenkins&gt; 入门一
  5. NFS共享存储服务部署
  6. 几个非常实用的JQuery代码片段
  7. c++ 高精度 加减乘除 四则运算 代码实现
  8. Python+selenium(Autolt实现上传)
  9. HaHa&#39;s Morning(状压DP)
  10. 【HDOJ6342】Expression in Memories(模拟)