Ross McFarlane
Ross McFarlane

Reputation: 4254

C: How long can a double be when printed through printf()

I need to specify the exact length of a string to be printed from a double value, but I don't want to restrict the output any more than is necessary.

What is the maximum length that a 6-digit precision double will have when formatted by printf()?

Specifically, what value should I give to X in printf("%X.6lg",doubleValue); to ensure that no value gets truncated?

The reason I need to be specific about the length is that I'm defining an MPI derived datatype made up of lots of string representations of double values and must know their exact length in order to divide regions of the file between MPI processes.

I hope that's clear. Thanks in advance for answering.

Upvotes: 5

Views: 7097

Answers (3)

Demi
Demi

Reputation: 6227

use printf("%.6g", doubleValue) or printf("%.6Lg", doubleValue)

Note that leaving off the leading digits (the "width") in the precision specifier makes no demands on the length of the integral portion of the value.

Also note that the undercase "l" will specify that your value is a long int. The uppercase "L" specifies a long double value.

Also note that if you don't want this to be potentially changed to scientific notation (if it is a shorter representation), then you would use "f" instead of "g".

See a printf reference here.

Upvotes: 6

DevSolar
DevSolar

Reputation: 70283

There's < float.h > containing many useful values, among them DECIMAL_DIG, which is for a long double however.

The same file will most likely tell you that a double on your platform has more than 6 digits of precision...

PS: Also note Demi's answer above. He points out various flaws in your printf() that escaped me.

Upvotes: 1

Michiel Buddingh
Michiel Buddingh

Reputation: 5919

The maximum exponent of an IEEE double is 1023, so largest double will be 1 + 1/2 + 1/4 + 1/8 + ... etc * 2^1023. Which will be about 318 characters long, in decimal notation.

Why not use the "e" format specifier?

Upvotes: 1

Related Questions