+ 1
What are the different ways to round off the floating values ?
Round off decimals !
4 Answers
+ 2
In most languages there should be:
rounding
flooring
ceiling
straight conversion to integer
straight conversion to int means just ignoring the decimal places, in Python this is done with int constructor:
int(5.5) ---> 5
int(-5.5) ---> -5
In some other languages, such as Java and C++ this is done using type casting:
(int) 5.5 ---> 5
(int) -5.5 ---> -5
With straight integer conversion the decimal part never affects the result.
+ 2
there are three main functions in rounding floats to a whole number.
- round() its result varies depending on the value of the float.
example, round(3.6) = 4 | round(3.4) = 3
- floor() it always returns the result rounded down
example : floor(3.4) = 3 | floor(3.9) = 3
- ceil() it always rounds up the value
example: ceil(3.4) = 4 | ceil(3.8) = 4
they're in math library in most languages.
+ 1
To understand:
rounding
flooring
ceiling
It may be useful to learn to understand decimal number A.B (Bâ 0) to be a value between 2 integers A and C:
if A.B > 0: C = A + 1
elif A.B < 0: C = A - 1
For example 5.5 is a value between 5 and 6.
When you convert a decimal number into an integer you will likely want to choose either of the integers A and C.
Then the meaning of these 3 operators get very simple:
floor: Chooses the smaller integer.
ceil: Chooses the greater integer.
round: Chooses the integer closer to A.B,
but in a special case, where B = 5, rounding takes the integer with the greater absolute value.
examples:
floor(5.9) ---> 5, because 5 < 6.
floor(-5.9) ---> -6, because -6 < -5.
ceil(5.1) ---> 6, because 6 > 5
ceil(-5.1) ---> -5, because -5 > -6