like 52.7-->53, 5.5-->6, 3.2->3
Asked
Active
Viewed 143 times
1
-
1Write your own..... – Sourav Ghosh Mar 31 '17 at 06:30
-
2@AliVolkanATLI *without using known functions*. – Weather Vane Mar 31 '17 at 06:34
-
1Similar? http://stackoverflow.com/questions/4572556/concise-way-to-implement-round-in-c – Bijay Gurung Mar 31 '17 at 06:42
-
2By the time you post it here, it will be known. – moooeeeep Mar 31 '17 at 06:42
-
Which way do you want to round negative numbers? – abelenky Mar 31 '17 at 06:43
2 Answers
0
To handle negative numbers properly (-52.7 ==> -53 (away from zero)
), you must check if the initial value is negative:
((int)(num + ((num > 0)? +0.5 : -0.5)))

abelenky
- 63,815
- 23
- 109
- 159
-2
int round(float num) {
return (int)(num + 0.5);
}
Edit: This will not work for large value of float and negative numbers.
Edit Again: This was the simple idea of how rounding works, but after reading comment on question this thread : Concise way to implement round() in C?
has everything explained for a proper implementation of round()
function

Community
- 1
- 1

Inder Kumar Rathore
- 39,458
- 17
- 135
- 184
-
2Note that this rounding mode is *round upwards*, not *round away from zero*, which might not be what someone expects. Also, it won't work for large values which `int` cannot represent. – user694733 Mar 31 '17 at 06:45
-
1You need to check double to int conversion, since possible loss of data – avatli Mar 31 '17 at 06:46