String series in practice c ++ -- specify valid floating point numbers and convert them to string
For example, to display the file size, we can obtain the total bytes of the file from the server. In this way, we need to display bytes, kb, mb, and other units according to the actual situation.
The common practice is to convert num_bytes/1024 to a float type, which can be converted to a string type. However, if you need to retain one or several decimal places of the float type, how can this operation be convenient?
You searched, but many people give you the answer either using cout or using printf to format the output.
We use 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
#include
#include
#include
// this should be already included in
// Defining own numeric facet:class WithComma: public numpunct
// 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 stringostringstream Convert;locale MyLocale( locale(), new WithComma);// Crate customized localeConvert.imbue(MyLocale); // Imbue the custom locale to the stringstreamConvert << fixed << setprecision(3) << Number; // Use some manipulatorsstring Result = Convert.str(); // Give the result to the string// Result is now equal to 0,120
Setprecision
Controls the number of valid numbers displayed in the output stream. If used with fixed, you can control the number of digits on the right of the decimal point.
However, the header file must be noted here:
#include