Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output a floating point value with a constant number of characters in C++

I'm having trouble doing what I think should be a fairly simple task in C++. I'm trying to output a floating point value to be written into a log file. The log file has 7 characters designated for the number output, but I'm finding it to be a little nontrivial to get a constant 7 character output over a wide range of values of different magnitudes, signs, and precisions (eg: 1, -0.60937, 0.60937, 0.009371, -0.009371). I've got a somewhat hacked way to kinda do it:

int desiredPrecision = 6;
if (runningAvg < 0)
  desiredPrecision--;
if (std::abs((long) runningAvg) < 1)
  desiredPrecision--;
else
  theFile << std::showpoint;

theFile.precision (desiredPrecision);

theFile.fill('0');
theFile.setf(std::ios_base::left, std::ios_base::adjustfield);
theFile.width(7);
theFile << runningAvg << std::endl;

But this way seems extremely hacky to me. It works with numbers like: -0.60937 (outputs: -0.6094)

-1.7 (-1.7000)

-1 (-1.0000)

0.6937 (0.60937)

0.00937 (0.00937)

but it breaks with 0.009371 (0.009371)

and

-0.009371 (-0.009371)

Now, I could add another level of if-else statements to deal with small magnitude numbers, but that just seems to be adding to the level of hackiness, and not a clean way to do it. I've played a bit with fprintf, but it seems like it is more concerned with a strict mathematical definition of precision, whereas in this application I care more about restricting the width of the field to 7 characters at all times. (I can also rely on these numbers never being so large that I'll overflow 6 characters plus a sign)

Am I missing something obvious here? Anyone have any tips for a less hacked way to achieve this?

like image 338
bencpeters Avatar asked Oct 21 '25 03:10

bencpeters


1 Answers

Don't know how to do this with iostream stuff but I think that the ?printf format string you're looking for is one of these:

  • %.4f for negative numbers and %07.5f for positive numbers.
  • %+.4f (positive numbers will have a leading +)
  • % .4f (positive numbers will have a leading space)
like image 67
trutheality Avatar answered Oct 23 '25 19:10

trutheality



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!