Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::format precision must be a constexpr?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading