Thread: round .5

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    43

    round .5

    Hi,

    I'm trying to find a prebuit cpp function (or C) which manipulates output:
    for the input of
    Code:
    double a = 1.55555555
     b= (manipulated a)
    cout << b;
    i would like the output to be
    1.56
    in other words, I want set prescision to .2 (with sprintf,or setpressicioon, or whatever)
    make sure that .5 is rounded upwards
    Is there a buildin function for this in STD of MATH or is this somthing i must write?

    Thanks

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    43

    excel FIXED

    I just noticed that this is exactly what MS excel does with the FIXED function....
    How can I emulate this

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    So do you actually want the value in the variable to change or do you simply want to display the already existing value to the specifications you've given (without actually changing the value stored in the variable)?

    This will simply display the value in the variable as you've requested without really changing it:
    Code:
    #include <iomanip>
    
    ...
    
    cout << fixed << setprecision(2) << b;
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Code:
    double round( double v, int p = 0 )
    {
    	static const double
    		t = 10, 
    		h = 0.5;
    	double
    		s = pow( t, p );
    	v *= s;
    	double
    		w = floor( v ), 
    		f = v - w;
    	if( f >= h )
    		++w;
    	v = w / s;
    	return v;	
    }
    Example:
    round( 555.555, 2 ) == 555.56
    round( 555.554, 2 ) == 555.55
    round( 555.554 ) == 556
    round( 555.555, -2 ) == 600
    round( 545.555, -2 ) == 500
    Last edited by Sebastiani; 06-12-2009 at 12:15 PM. Reason: formatting
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You may also be interested in: Most Efficient Way to Check a Variable Is A Whole Number

    @Sebastiani: Very nice code! Just two notes:
    Code:
    $ cat round.cpp
    #include <iostream>
    #include <cmath>
    
    using std::pow;
    using std::floor;
    
    double my_round( double v, int p = 0 )
    {
            static const double
                    t = 10,
                    h = 0.5;
            double
                    s = pow( t, p );
            v *= s;
            double
                    w = floor( v ),
                    f = v - w;
            if( f >= h )
                    ++w;
            v = w / s;
            return v;
    }
    
    int main() {
        std::cout << my_round(-1.5) << std::endl;
        return 0;
    }
    $ ./round
    -1
    $
    The first is that you always round upwards, whereas I think -1.5 should be rounded downwards, should it not? Also, there's a standard function called "round" so unless you use a different name, you'll probably get compiler errors (unless you don't #include <cmath>, which is difficult since the code uses pow and floor).

    Oh, and I'd have used more descriptive variable names . . . .
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Multiply by 100.0, round to nearest integer, divide by 100.0
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Yeah, that's probably the way I would do it (if I actually needed the rounded value for other calculations, that is). Details of "round to nearest integer" are in that thread I linked to.

    For completeness (since the OP mentioned sprintf()), here's how you would do it with printf() (sprintf() is a simple modification from here):
    Code:
    printf("%.2f\n", 3.14159);  /* prints 3.14 */
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by brewbuck View Post
    Multiply by 100.0, round to nearest integer, divide by 100.0
    That would just add 2 steps to what is needed to round anyway
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Ah, but rounding to the nearest integer is very easy to do. Here's an example of mine from that thread that I posted which I wish everyone would read (): Most Efficient Way to Check a Variable Is A Whole Number

    Basically: modf is one easy way to do it.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by ಠ_ಠ View Post
    That would just add 2 steps to what is needed to round anyway
    And your more efficient proposed method for rounding to the N'th decimal place looks like what?
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> The first is that you always round upwards, whereas I think -1.5 should be rounded downwards, should it not?

    Apparently, the answer to that is "it depends" (I believe mine would be the "round half up asymmetric" algorithm, as used in Java). The choice seems a bit arbitrary, though, since 0.5 is exactly in the middle (and so either way could be considered a correct approach), although the way you suggested is probably more consistent.

    >> Also, there's a standard function called "round" so unless you use a different name, you'll probably get compiler errors (unless you don't #include <cmath>, which is difficult since the code uses pow and floor).

    I'm an idiot. I completely forgot that was a standard function!

    >> Oh, and I'd have used more descriptive variable names . . . .

    I figured it might be a fairly common homework question so I decided to make it somewhat more obscure (although not obfuscated).
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  12. #12
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> Multiply by 100.0, round to nearest integer, divide by 100.0

    But doesn't that just truncate the value (without rounding)?

    EDIT:
    Ignore that. I'm having trouble understanding english today.
    Last edited by Sebastiani; 06-12-2009 at 01:30 PM.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  13. #13
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by brewbuck View Post
    And your more efficient proposed method for rounding to the N'th decimal place looks like what?
    actually, the way you said to do it is the only way I can see to do it

    oops
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  14. #14
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Apparently, the answer to that is "it depends" (I believe mine would be the "round half up asymmetric" algorithm, as used in Java). The choice seems a bit arbitrary, though, since 0.5 is exactly in the middle (and so either way could be considered a correct approach), although the way you suggested is probably more consistent.
    Yes, indeed. I was just going by the std::round function, which I'm pretty sure has the behaviour I described (round .5 away from zero).

    I figured it might be a fairly common homework question so I decided to make it somewhat more obscure (although not obfuscated).
    I suppose, though I think that anyone marking code like that (nice indentation, static const variables, default values) would be able to tell from the rest of someone's code whether or not they actually wrote it . . . .

    [edit]
    >> Multiply by 100.0, round to nearest integer, divide by 100.0

    But doesn't that just truncate the value (without rounding)?
    Consider 1.234. Multiply it by 100, and you get 123.4. Round this to the nearest integer; you have 123. Divide this by 100 again, and you get 1.23. I think that works, don't you? (At least in theory).

    I'm not sure I really understood your question. [/edit]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by dwks View Post
    [edit]
    Consider 1.234. Multiply it by 100, and you get 123.4. Round this to the nearest integer; you have 123. Divide this by 100 again, and you get 1.23. I think that works, don't you? (At least in theory).

    I'm not sure I really understood your question. [/edit]
    Consider 1.55555555 instead.
    The answer with rounding should be 1.56, not 1.55
    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"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  2. Fibonacci Formula, How to round in C++?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 10-15-2004, 10:47 AM
  3. I need some quick help with code.
    By stehigs321 in forum C Programming
    Replies: 35
    Last Post: 10-30-2003, 10:07 PM
  4. Someone help me with this game??
    By stehigs321 in forum Game Programming
    Replies: 15
    Last Post: 10-30-2003, 09:42 PM
  5. Please help with some coding..
    By stehigs321 in forum C Programming
    Replies: 2
    Last Post: 10-27-2003, 06:44 PM