Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

mpi

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.

like image 794
Ross McFarlane Avatar asked Jun 18 '09 13:06

Ross McFarlane


People also ask

How do I print a long double in printf?

%Lf format specifier for long double %lf and %Lf plays different role in printf. So, we should use %Lf format specifier for printing a long double value.

How do you print a long double value?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

What is the long double in C?

In C and related programming languages, long double refers to a floating-point data type that is often more precise than double precision though the language standard only requires it to be at least as precise as double .

How do I print a long in printf?

Put an l (lowercased letter L) directly before the specifier. printf("%ld", ULONG_MAX) outputs the value as -1. Should be printf("%lu", ULONG_MAX) for unsigned long as described by @Blorgbeard below. Actually, you should change it to be %ld , to be more harmonic with OP question.


1 Answers

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.

like image 131
Demi Avatar answered Sep 30 '22 01:09

Demi