Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <limits>
  2. #include <string>
  3. #include <algorithm>
  4. #include <type_traits>
  5. #include <cmath>
  6.  
  7. template<typename T, std::enable_if_t<std::is_floating_point<T>::value, int> = 0>
  8. std::string ToString(T value)
  9. {
  10.     std::string s;
  11.  
  12.     // Break into integral and fractional parts
  13.     T i;
  14.     T f = std::modf(value, &i);
  15.  
  16.     // Handle negatives
  17.     bool neg = false;
  18.     if (i < 0) {
  19.         i = -i;
  20.         neg = true;
  21.     }
  22.  
  23.     // Convert the integral part
  24.     do {
  25.         s.push_back('0' + static_cast<int>(std::fmod(i, 10)));
  26.         i = std::floor(i / 10);
  27.     }
  28.     while (i > 0);
  29.  
  30.     // Append '-' for negatives
  31.     if (neg) {
  32.         s.push_back('-');
  33.     }
  34.  
  35.     // Reverse integral part and add decimal point
  36.     std::reverse(s.begin(), s.end());
  37.     s.push_back('.');
  38.  
  39.     // Convert the fractional part
  40.     do {
  41.         f = std::modf(f * 10, &i);
  42.         s.push_back('0' + static_cast<int>(i));
  43.     }
  44.     while (f > 0);
  45.  
  46.     return s;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement