##實戰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>
~~~
- 前言
- string與整型或浮點型互轉
- 指定浮點數有效數字并轉為string
- string的替換、查找(一些與路徑相關的操作)
- string的分割、替換(類似string.split或是explode())
- string的初始化、刪除、轉大小寫(construct erase upper-lower)
- string的遍歷(使用下標還是iterator)
- std::string與MFC中CString的轉換
- string到LPCWSTR的轉換
- std:vector<char> 和std:string相互轉換(vector to stringstream)
- CDuiString和string的轉換(duilib中的cduistring)
- string的連接(+= or append or push_back)
- 函數返回局部變量string(引用局部string,局部string的.c_str()函數)
- 將string用于switch語句(c++做C#的事兒, switch中break還是return厲害)
- 不要使用memset初始化string(一定別這么干)