String series in practice c ++ -- specify valid floating point numbers and convert them to string

Source: Internet
Author: User

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 
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.