PRB: Bad Results When %lf Is Format Specifier for Long Double

ID: Q128791

7.00 | 1.00 1.50 1.51 1.52 MS-DOS | WINDOWS kbtool kbprb

The information in this article applies to:

SYMPTOMS

Unpredictable results occur when %lf is used as a format specifier for a long double in functions such as sprintf() or printf() as in this example:

   sprintf(chr_buffer, "The value of long double variable is %.3lf ",
                       lng_dbl);

CAUSE

The format specifier for a long double is Lf, and the format specifier for a double is lf. The format argument tells the function the size and type of the arguments. A long double is 10 bytes and a double is 8 bytes so they need different format specifiers.

RESOLUTION

Use %Lf as the format specifier for a long double.

STATUS

This behavior is by design.

MORE INFORMATION

Sample Code

/* Compile options needed: none
*/ 

#include <stdio.h>
void main(void)
{
     long double lng_dbl = 2.345;
     char ch_arr[100];

 //  Line with the problem resulting from the incorrect specifier
     sprintf(ch_arr, "%.3lf", lng_dbl);
     printf("The value of 2.345 is not %s \n", ch_arr);

 //  Line with the correct format specifier
     sprintf(ch_arr, "%.3Lf ", lng_dbl);
     printf("The value of 2.345 is %s", ch_arr);
 }

Additional reference words: 7.00 1.00 1.50 1.51 1.52 KBCategory: kbtool kbprb KBSubcategory: CRTIss Keywords : kb16bitonly

Last Reviewed: July 23, 1997