I have a function, which is used to get the fixed digit’s string of input double.
the function is:
std::string to_fixed_string(double s, size_t n) {
char buff[64];
snprintf(buff, sizeof(buff), ("%." + std::to_string(n) + "f").c_str(), s);
return buff;
}
recently i am using std::format, the most important reason is std::format is faster than snprintf.
but i found the constexpr limit make this function not work.
is there any more effiective method to implement this function?
example is:
func(1.123123131, 3) -> "1.123"
func(1.123123131, 5) -> "1.12312"
>Solution :
std::format("{:.{}f}", value, precision), note {} instead of the precision number.
printf has an equivalent feature, you can put * instead of the number (but unlike format the precision argument goes before the value argument, not after). If you continue to use printf for some reason, you should be doing this instead of generating the format string.