String formatting for uint64_t that represents a fixed-point decimal My goal is to take a uint64_t that represents a fixed-point decimal, and output a string representation of the decimal. The fixed-point representation always has eight decimal places, so for example 1.12345678 is represented as 112345678.

How can I make the following code cleaner and/or faster? Obviously all the character insertions/deletions are very slow, but what's the best way to get rid of those?

std::string uint64_to_string(uint64_t n) {
  auto retval = std::to_string(n);  // Initial conversion to string

  if(retval.size() &lt;= 8) {
    // Add leading zeros if necessary, so for example n=1 becomes 000000001
    size_t num_leading_zeros = 9 - retval.size();
    retval.insert(0, num_leading_zeros, '0');
  }

  // Insert decimal, so 000000001 becomes 0.00000001
  retval.insert(retval.size() - 8, 1, '.');

  // Trim trailing zeros, and trim '.' if it is the last character
  boost::trim_right_if(retval, [](char c) { return (c == '0' || c == '.'); });
  return retval;
}
std::string uint64_to_string(uint64_t n) {


Make interfaces easy to use correctly and hard to use incorrectly.  

The function name is confusing as it would lead me to believe that if I called uint64_to_string(1ull), I would expect a returned value of "1".  

From your problem statement:


  My goal is to take a uint64_t that represents a fixed-point decimal


Instead of using a built-in integer type, leverage the type system by using a fixed-point decimal class.



Ensure you are using &lt;cstdint&gt; and prefix the namespace on the integral type std::uint64_t.



Avoid magic numbers. If 8 is supposed to represent a fixed radix point, you should document that by assigning it to a descriptive variable name.  If you use a fixed-point decimal class, you could just refer to its radix point instead.




  How can I make the following code cleaner and/or faster? Obviously all the character insertions/deletions are very slow, but what's the best way to get rid of those?


If you've measured and multiple allocations are slowing you down, calculate the string length of your result first, then fill it with the characters.  I highly recommend you watch Andrei Alexandrescu's Fastware talk he's been giving for the past few years.  He covers this exact topic of converting integers to strings using specific optimization techniques.