Parsing the formatted display of C++ floating point Numbers

  • 2020-04-02 01:05:55
  • OfStack

The code is as follows:

    #include <stdlib.h>  
    #include <string>  
    #include <windows.h>  
    #include <stdio.h>  
    #include <iostream>  
    #include <limits>  
    #include <sstream>  
    using namespace std;  

    string do_fraction(long double val, int decplaces=3)  
    {  
        ostringstream  out;  
        char DECIMAL_POINT='.'; //European usage is', '& NBSP;
        int prec=numeric_limits<long double>::digits10; // 18  
        out.precision(prec);//Override default precision & NBSP;
        out<<val;  
        string str= out.str(); //Takes the string & PI from the stream;
        size_t n=str.find(DECIMAL_POINT);  
        if ((n!=string::npos) //Does it have a decimal point? & have spent
            && (str.size()> n+decplaces)) //Is there at least a decplaces in the back? & have spent
        {  
            str[n+decplaces]='0';//Overwrite the first extra number & NBSP;
        }  
        str.swap(string(str.c_str()));//Remove the extra character & NBSP; after nul;

        return str;  
    }  

Related articles: