infinitezero
infinitezero

Reputation: 2077

fmt::format how to always print first n non-zero digits with leading zeroes

Given three floating point numbers

a = 1.0
b = 1.23456
c = 1.23456e-12

How can I always print the first n non-zero digits, with leading zeroes, if required. Desired output for n=6:

1.00000
1.23456
0.00000000000123456

I tried fmt::format("{:.6f"}", number) but this returns 0.00000 in the last case.

Upvotes: 3

Views: 1056

Answers (1)

vitaut
vitaut

Reputation: 55725

There is no built-in way of doing this but you could do it in several steps:

  1. Format using the exponent notation (e).
  2. Extract the exponent.
  3. Format using the fixed notation (f) adjusting the precision to account for the exponent.

For example:

#include <fmt/core.h>

void print(double n) {
  auto s = fmt::format("{:e}", n);
  auto exp = atoi(s.substr(s.find('e') + 1).c_str());
  int precision = 6;
  if (exp < 0) precision -= exp;
  fmt::print("{:.{}f}\n", n, precision - 1);
}

int main() {
  print(1.0);
  print(1.23456);
  print(1.23456e-12);
}

This prints:

1.00000
1.23456
0.00000000000123456

https://godbolt.org/z/16n8s7TG3

Upvotes: 4

Related Questions