Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

(C++) How would I display a value rounded to the nearest integer?

  1. Sep 21, 2008 #1
    Like for example

    Prompting message reads.

    "Please enter a positive value"


    Please enter a positive value: 234.7
    Rounded to the nearest integer the number is: 235

    Please enter a positive value: 10.3
    Rounded to the nearest integer the number is: 10

    What I have

    int num;

    cout<< "Please enter a positive value";

    cin>> num;

    cout<< num << endl;

    The problem is that doesn't round the number to the nearest interger so what would I do to round it?
  2. jcsd
  3. Sep 21, 2008 #2
    (int) (3.5+0.5)
  4. Sep 21, 2008 #3
    Dude that's not it.
    Last edited: Sep 21, 2008
  5. Sep 21, 2008 #4


    User Avatar
    Science Advisor
    Homework Helper

    rootX gave a correct example of the calculation needed. You need to input as a float, not an int, then convert to an int by rounding as in rootX's suggestion.
  6. Sep 21, 2008 #5


    User Avatar

    It does help if num is a floating point variable, rather than an int.

    Round to zero (truncation)
    Code (Text):
    int rounded_num = static_cast<int>(num);
    Round to +infinity
    Code (Text):
    int rounded_num = std::floor(num + 0.5);
    Round away from zero
    Code (Text):
    int rounded_num = (num < 0.0)
        ? ((std::floor(num) == num - 0.5) ? std::floor(num) : std::floor(num + 0.5))
        : std::floor(num + 0.5);
    Really shouldn't do direct == with floating points, but that's another subject.

    Or in C++0x:
    Code (Text):
    int rounded_num = std::round(num);
    Round to even
    Um, have fun....
  7. Sep 26, 2008 #6


    User Avatar

    very insteresting, but I think rootx's answer is enough and simple.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?