実戦c++のstringシリーズ--浮動小数点数の有効数字を指定しstringに変換

2710 ワード

前のブログではnumberからstringへの変換についていくつかの方法を説明しましたが、ここではfloatやdoubleからstringへの変換を単独で話します.
やはりコントロール表示の原因で、例えばファイルのサイズを表示するには、サーバからこのファイルの総bytesを得ることができます.これにより,bytes,kb,mbなどの単位を実際の状況に応じて表示する必要がある.
よく使われる方法はnum_bytes/1024、この时よく浮動小数点型を得ることができて、浮動小数点型はstringを回転しても大丈夫ですが、もしあなたがこの浮動小数点型の1位あるいは何位の小数点を保留する必要があるならば、どのように操作するのは便利で速いですか?
あなたは関連検索を行いましたが、多くの人があなたに答えたのは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>