Print a long duble

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
New poster
Posts: 7
Joined: Sat Apr 01, 2006 8:00 pm

Print a long duble

Post by d31mOZ » Sat Apr 01, 2006 11:32 pm

How i can print a variable "long double", for example:

Code: Select all

#include <iostream.h>

int main()
        long double n1 = 100000000;
        cout << n1;
        return 0;

The program is good, but print:

I want that print:

What i can do it?


New poster
Posts: 27
Joined: Sat Mar 18, 2006 5:04 pm

Post by andresw1 » Sun Apr 02, 2006 10:17 am


You can use the stdio.h instead of iostream. With stdio.h you can print long double in the following way:

long double d = 100.0;

printf("%Lf",d); -> This wil print something like 100.00000000
To cut the 0's in the end you can modify the %lf in the following way
printf("%.3Lf",d); -> The number after the dot is how many digits you want to print after the hole part.

If someone knows hoe to do it with iostram I would also be intrested to understand... Now when I have doubles in the problem I use stdio, otherwise iostream...

[Edit] "Lf" instead of "lf" after misof noticed my mistake. I'm sorry.
Last edited by andresw1 on Sun Apr 02, 2006 4:11 pm, edited 1 time in total.

A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm

Post by misof » Sun Apr 02, 2006 1:36 pm

The correct format string for a "long double" is "%Lf", not "%lf". The format string "%lf" is for "double".

About doing it using streams, you really should consider using Google. E.g., try the query "cout fixed format".

User avatar
Krzysztof Duleba
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland

Post by Krzysztof Duleba » Sun Apr 02, 2006 3:30 pm

It's easy when you know that "fixed" is the keyword. However, even simple search at C++ board for iostream double returns the answer.

Post Reply

Return to “C++”