I look into std::format
trying to make short std::string
representation of floating point variable.
My problem is that I can’t set width, since I don’t know how many digits before decimal point. If I set precision, it prints zeroes even if they are the only trailing digits.
I guess this could be achieved somehow with width/precision/filling, etc., but can’t see the way.
Let’s say I want the string to fit in the specified fit_to
if only possible; if not the string should take the minimum possible digits, preferring “100” to “1e2” or “1000” to 1e03″ or “0.01” to “1e-2”, etc.
Could this be achieved with std::format (or any other kind of std formatting) without manual conversion of every digit from float?
#include <iostream>
std::string to_string_shortest(float v, [[maybe_unused]] std::size_t fit_to = 4) {
return std::format("{}", v);
}
int main()
{
std::cout << to_string_shortest(3.1415926f) << std::endl; // Want to have 3.14
std::cout << to_string_shortest(1e7f) << std::endl; // Want to have 1e+7 (1e7 acceptable)
std::cout << to_string_shortest(1e-7f) << std::endl; // Want to have 1e-7
std::cout << to_string_shortest(1.2345e20f) << std::endl; // Want to have 1e20
std::cout << to_string_shortest(1.2345e-20f) << std::endl; // Want to have 1e-20
std::cout << to_string_shortest(3.1415926f, 8) << std::endl; // Want to have 3.141593
std::cout << to_string_shortest(-3.1415926f, 8) << std::endl; // Want to have -3.14159
std::cout << to_string_shortest(1.2345e20f, 8) << std::endl; // Want to have 1.234e20
std::cout << to_string_shortest(1.2345e-20f, 8) << std::endl; // Want to have 1.23e-20
std::cout << to_string_shortest(0.001f) << std::endl; // Want to keep as is
std::cout << to_string_shortest(1.0f) << std::endl; // Want to keep as is
std::cout << to_string_shortest(1e20f) << std::endl; // Want to keep as is
std::cout << to_string_shortest(1e-20f) << std::endl; // Want to keep as is
}
Demo.
3