Python Round Floor Ceiling Truncate Functions

preview_player
Показать описание
In this Python tutorial, we will go over how to round a number, how to use the floor and ceiling functions with numbers and truncate numbers.
Рекомендации по теме
Комментарии
Автор

Thanks, helped a lot with my math bot by making it only show 3 decimals

prime
Автор

See python decimal module documentation for more options (rounding options, precision, etc.).

example:
import decimal
# round down or truncate at specified decimal place
def round_down(number, decimal_places):
decimal.getcontext().rounding = decimal.ROUND_DOWN
decimal_object = decimal.Decimal(str(number))
return float(round(decimal_object, decimal_places))

The default round method appears to be ROUND_HALF_EVEN which means 10.5 (even) will be rounded down and 11.5 (odd) will be rounded up. This may be unexpected but can be changed to other methods (examples-ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, ROUND_05UP)

Note that some spreadsheet ceiling, floor functions have an extra factor/significance argument which determines the closest multiple and allows for decimals.

RyanNoonan
Автор

How do we explain truncation in the exam for computer science

alisubhani
Автор

So if I am seeing it correctly the math.trunc function will just remove the decimal? but what is the function of the trunc if it is just that if you can simply use int() to get rid of the decimal?

irvingsandoval
Автор

What about rounding to highest integer?

mjb
Автор

someone please help, i am really struggling to find an answer to this one which to me should be so simple!
i need a round down function like the ROUNDDOWN function in excel where you can round down numbers to any amount of decimal places

for example:
(1dp) - 7.78882 rounds down to 7.7

(1dp) - 6.24343 rounds down to 6.2

(2dp) - 7.78882 rounds down to 7.78
(2dp) - 6.24343 rounds down to 6.24


(3dp) - 7.78882 rounds down to 7.788
(3dp) - 6.24343 rounds down to 6.243

etc

thank you

JagoBridgland