Thread: Round float to 2 decimal places

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    11

    Round float to 2 decimal places

    I just wanted to know how to round my result to 2 decimal places.


    Code:
    #include <stdio.h>
    #include <stdlib.h>	/* For atoi() */
    #include <ctype.h>	/* For toupper() */
    #include <string.h> /*For string operations*/
    #include<iostream>
    using namespace std;
    
    int main() {
    
        char*  money1= "3.05";
    	char* money2= "2.56";
    
    	float avg = strtod(money1,NULL)/strtod(money2,NULL);
    
    	cout << avg <<endl;
    
    }
    This gives the result of 1.19141 but the answer i want is just 1.19, how do I get the number rounded to 2 decimal places?


    Thanx again, u guys been really helpful
    Last edited by tesla; 09-14-2009 at 07:43 AM.

  2. #2
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,472
    with printf() you can specify the amount of decimal places >
    %.0f = no decimal places,
    %.4f equals float showing four decimal places;
    whether or not this is the exact value stored is another matter...but at least you will be displaying the rounded up one you want.

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    198
    There might be a more elegant way of doing this in C, but you are posting C++ code here in the C forum so I have an idea that might work on both:

    Code:
    float num = 3.14159;
    
    num *= 100;
    if(num >= 0) num += 0.5; else num -= 0.5;
    long round = num;
    num = round;
    num /= 100;

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    float and double are not designed to handle monetary amounts. They can accumulate rounding error and lose cents here and there. Other languages such as VB have a currency type specifically for money. In C/C++ one can usually get away with storing the number multiplied by 100 in an int. It's called "Fixed point math" if you want to look it up.
    Having said that, it doesn't make sense to divide monetary amounts anyway.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by iMalc View Post
    Having said that, it doesn't make sense to divide monetary amounts anyway.
    I invest $500. After two weeks, I cash out a total of $600. What percentage increase is this? Remember, it doesn't make sense to divide monetary amounts...
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  6. #6
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,337
    Quote Originally Posted by iMalc View Post
    ...it doesn't make sense to divide monetary amounts ...
    We have our weekly winner!
    Mainframe assembler programmer by trade. C coder when I can.

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I should have said "here" or "in this case". The variable name "avg" suggested that tesla was intending to calculate the average, for which there would obviously only be an addition and a division by the constant factor of 2 (or multiply by 0.5).

    Of course that doesn't explain why 1.19 was expected, but thats what you get from someone who is staying home sick!
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User
    Join Date
    Nov 2008
    Location
    Phoenix
    Posts
    70
    If you're just looking for cosmetic rounding, the others have provided solutions. But if you're looking for actual rounding, then C99 includes a rounding function in math.h. It rounds a float to the nearest integer. So you'll have to multiply by however many powers of 10 (depending on the precision you want in the end result), do the round, then divide back down.

    I actually came across a similar problem in my intro C class last fall. Our third assignment had several monetary calculations and part of the point of the assignment was, among other things, to notice C's floating point math issues and try to solve them. Doing the assignment in a straightforward way had the result end up being 1 cent too high, because of the accumulated floating point math issues and lack of real rounding. Well I did some research and found that C99 has a rounding function. I informed my professor and he was thrilled. It was a lot simpler than the things other people were doing. Although he preferred older standards of C (having used them in the work place for decades), he was generally up to date on what C99 was about, aside from a few small details here and there, such as rounding.

  9. #9
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Sorin View Post
    I actually came across a similar problem in my intro C class last fall. Our third assignment had several monetary calculations and part of the point of the assignment was, among other things, to notice C's floating point math issues and try to solve them. Doing the assignment in a straightforward way had the result end up being 1 cent too high, because of the accumulated floating point math issues and lack of real rounding. Well I did some research and found that C99 has a rounding function. I informed my professor and he was thrilled. It was a lot simpler than the things other people were doing. Although he preferred older standards of C (having used them in the work place for decades), he was generally up to date on what C99 was about, aside from a few small details here and there, such as rounding.
    Correct rounding of money amounts is really a combination of two factors. First, the quantities should be represented in terms of the smallest indivisible unit of currency (in the case of the dollar, US or otherwise, this is a single cent). Second, rounding is never defined in terms of IEEE floating point behavior, but deliberately defined in somewhat arbitrary ways to suit the situation.

    Because we're dealing with money, rounding things the "wrong" way, as defined by various laws or contracts, could actually qualify as fraud. Fraud is not something that is addressed by the IEEE standards. Thus relying on any specific IEEE behavior is likely to yield incorrect results.

    (In other words, perhaps the students passed the assignment, but would you really be comfortable deploying that software in a banking environment? Are you SURE you have the math right?)
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Decimal places
    By Gordon in forum Windows Programming
    Replies: 9
    Last Post: 06-08-2008, 09:04 AM
  2. Float Function Issues
    By GCNDoug in forum C++ Programming
    Replies: 5
    Last Post: 10-29-2007, 03:25 PM
  3. Need help with program
    By HAssan in forum C Programming
    Replies: 8
    Last Post: 06-10-2007, 08:05 PM
  4. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  5. Repetition in do{}while
    By Beast() in forum C Programming
    Replies: 25
    Last Post: 06-16-2004, 10:47 PM