| | |
Rounding
Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Mar 2008
Posts: 1,497
Reputation:
Solved Threads: 123
Rounding a number to the nearest whole number is one of the easiest things you can do in C++
there isn't even any need for an if/else statement, take this as an example.
Hope this helps.
there isn't even any need for an if/else statement, take this as an example. C++ Syntax (Toggle Plain Text)
float decimal = 3.4f; int rounded = int(decimal + 0.5f); // 3
Last edited by William Hemsworth; Sep 16th, 2008 at 5:40 pm.
1. Regrettably, for negative numbers williamhemsworth's solution does not work (moreover, gives wrong result - for example, it yields 0 for -0.9 but nearest integer value for -0.9 is -1). Right solution:
2. In this context a rounding to the nearest integer is not the same thing as a rounding to the nearest int type value. For example, on 32-bit CPU max int is 2147483647 (INT_MAX macros from limit.h). So you can't round 3333333333.3 to int 3333333333 (no such int value) - but you can round it to 3333333333.0. Of course, if you want to round to int, you may use the same method as in round function defined above (no need in floor library call in that case).
C++ Syntax (Toggle Plain Text)
#include <cmath> ... double round(double x) { bool negative = false; if (x < 0.0) { x = -x; negative = true; } x = std::floor(x+0.5); return negative? -x: x; }
![]() |
Similar Threads
- Rounding up problem (C++)
- Rounding and displaying floats (C)
- rounding array elements (C++)
- NumberFormat - Incorrect rounding (Java)
- Rounding floating points (C++)
- Applet Rounding Issue (Java)
- Rounding with Microsoft Visual Studio .NET 2003 (C++)
- Number Rounding (Java)
Other Threads in the C++ Forum
- Previous Thread: C/C++ libraries
- Next Thread: file io line by line
Views: 1029 | Replies: 3
| Thread Tools | Search this Thread |
Tag cloud for C++
6 add api array arrays beginner binary bitmap c++ c/c++ calculator char class classes code compile compiler console conversion convert count data delete desktop directshow dll encryption error file forms fstream function functions game getline givemetehcodez google graph homeworkhelper iamthwee ifstream input int integer java lazy lib linkedlist linux loop looping loops map math matrix memory microsoft newbie news node number output parameter pointer problem program programming project proxy python random read recursion recursive reference return sort string strings struct studio system template templates test text tree unix url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






