实战c++中的string系列--指定浮点数有效数字并转为string
2015-12-09 21:51
429 查看
上一篇博客讲了好几种方法进行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
setprecision
控制输出流显示浮点数的有效数字个数 ,如果和fixed合用的话,可以控制小数点右面的位数
但是这里需要注意的是头文件:
还是处于控件显示的原因,比如说要显示文件的大小,我们从服务器可以获得这个文件的总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>
相关文章推荐
- (学习)C++ Primer(1)
- 实战c++中的string系列--string与整型或浮点型互转
- 实战c++中的string系列--string与整型或浮点型互转
- C语言快排模板 qsort();函数应用
- HDU2089 不要62【数位DP】
- c++ 11 右值引用原理
- 设计Qt风格的C++API
- C++ offsetof
- c语言的笔记
- 一个刚出生的奶牛,4年生一只,以后每年生一只,现在有一只刚出生的奶牛,问20年以后一共多少只奶牛?
- c++
- VC++ 最小化到托盘、恢复
- C语言的这些事情有关内存
- C++中的强制类型转换
- VC++ 实现VC程序启动时最小化到任务栏(完美解决闪烁问题)
- c++
- C语言词法及语法定义-Lex,Yacc
- c++11多线程入门实例
- C语言学习笔记(20) 数组参数和指针参数分析
- C++中随机数的生成