Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <limits>
- #include <string>
- #include <algorithm>
- #include <type_traits>
- #include <cmath>
- template<typename T, std::enable_if_t<std::is_floating_point<T>::value, int> = 0>
- std::string ToString(T value)
- {
- std::string s;
- // Break into integral and fractional parts
- T i;
- T f = std::modf(value, &i);
- // Handle negatives
- bool neg = false;
- if (i < 0) {
- i = -i;
- neg = true;
- }
- // Convert the integral part
- do {
- s.push_back('0' + static_cast<int>(std::fmod(i, 10)));
- i = std::floor(i / 10);
- }
- while (i > 0);
- // Append '-' for negatives
- if (neg) {
- s.push_back('-');
- }
- // Reverse integral part and add decimal point
- std::reverse(s.begin(), s.end());
- s.push_back('.');
- // Convert the fractional part
- do {
- f = std::modf(f * 10, &i);
- s.push_back('0' + static_cast<int>(i));
- }
- while (f > 0);
- return s;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement