Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum Width of a Printed Double in C++

Tags:

c++

I was wondering, how long in number of characters would the longest a double printed using fprintf be? My guess is wrong.

Thanks in advance.

like image 797
Cenoc Avatar asked Dec 02 '22 05:12

Cenoc


2 Answers

Twelve would be a bit of an underestimate. On my machine, the following results in a 317 character long string:

#include <limits>
#include <cstdio>
#include <cstring>

int main() 
{
    double d = -std::numeric_limits<double>::max();
    char str[2048] = "";

    std::sprintf(str, "%f", d);

    std::size_t length = std::strlen(str);
}

Using %e results in a 14 character long string.

like image 185
James McNellis Avatar answered Jan 01 '23 07:01

James McNellis


Who knows. The Standard doesn't say how many digits of precision a double provides other than saying it (3.9.1.8) "provides at least as much precision as float," so you don't really know how many characters you'll need to sprintf an arbitrary value. Even if you did know how many digits your implementation provided, there's still the question of exponential formatting, etc.

But there's a MUCH bigger question here. Why the heck would you care? I'm guessing it's because you're trying to write something like this:

double d = ...;
int MAGIC_NUMBER = ...;
char buffer[MAGIC_NUMBER];
sprintf(buffer, "%f", d);

This is a bad way to do this, precisely because you don't know how big MAGIC_NUMBER should be. You can pick something that should be big enough, like 14 or 128k, but then the number you picked is arbitrary, not based on anything but a guess that it will be big enough. Numbers like MAGIC_NUMBER are, not suprisingly, called Magic Numbers. Stay away from them. They will make you cry one day.

Instead, there's a lot of ways to do this string formatting without having to care about buffer sizes, digits of precision, etc, that let you just get on with the buisness of programming. Streams is one:

#include <sstream>

double d = ...;
stringstream ss;
ss << d;
string s = ss.str();
cout << s;

...Boost.Format is another:

#include <boost\format\format.hpp>

double d = ... ;
string s = (boost::format("%1%") % d).str();
cout << s;
like image 31
John Dibling Avatar answered Jan 01 '23 07:01

John Dibling