Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 135,963 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,517 people online right now. Registration is fast and FREE... Join Now!




decimal display problem

 
Reply to this topicStart new topic

decimal display problem, display 2 decimal places to the right

Renzokusen
10 May, 2008 - 09:56 AM
Post #1

New D.I.C Head
*

Joined: 11 Mar, 2008
Posts: 32

I'm currently have problems displaying ONLY 2 decimal places to the right of a decimal in either a float or a double variable. My teacher hasn't come to me with a decent response other than << fixed; which display to many places.

I'm working with currency which is only 2 decimal places. My float will display 23.23 perfectly, but when the amount ends in a 0 it will display 23.2 instead of displaying the correct 23.20.

If you need some code to understand this better just say so. I don't think I need to post any since it's kinda not a code problem an more of a .... not sure how to discribe it. biggrin.gif

Thank you
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Decimal Display Problem
10 May, 2008 - 10:12 AM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,173



Thanked: 208 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Best way to show you is with a simple example...

cpp

#include <iostream>
// Needed to manipulate the output of cout
#include <iomanip>

using namespace std;

int main( )
{
// Our float
float PI = 3.1415;

// Set precision to 2 places, fixed decimal point, show PI
cout << setprecision(2) << fixed << PI << endl;
return 0;
}


We use setprecision(2) to say 2 decimal points and fixed for a fixed decimal place. This will give you the two decimal points with rounding.

Enjoy!

"At DIC we be fixed point code ninjas, mess with us and we will 'fix' you to the 'point' where you will be unrecognizable!" decap.gif
User is online!Profile CardPM
+Quote Post

Renzokusen
RE: Decimal Display Problem
10 May, 2008 - 10:27 AM
Post #3

New D.I.C Head
*

Joined: 11 Mar, 2008
Posts: 32

Ah I see what the problem was. My teacher gave me that code, but never told me about #include <iomanip> . No wonder it wouldn't work.

Thanks for the help it works fine now
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/1/08 09:37AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month