C++: Converting a double/float to string, preserve scientific notation and precision

前端 未结 2 1375
不思量自难忘°
不思量自难忘° 2021-01-27 11:46

I\'m trying to convert double/float numbers to string. Some of these numbers contain scientific notation \"e\", and I want to preserve it after the conversion. I searched throug

2条回答
  •  梦毁少年i
    2021-01-27 12:30

    Your code is running fine. If you have crap values in the output maybe there is a stack corruption somewhere else.

    #include 
    #include 
    #include 
    
    template 
    inline std::string ToString(T value) {
      std::stringstream out;
      out << std::fixed;  
      out << value;
      return out.str();
    }
    
    int main() {
      double mydouble = 1.7976931348623157e+308; 
      std::cout << boost::lexical_cast(mydouble) << '\n'; 
      std::cout << ToString(mydouble) << '\n';
    }
    

    Output:

    1.7976931348623157e+308 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000

    As it was pointed out by Marcus in previous comments you don't want to use std::fixed.

提交回复
热议问题