Round in python

April 8, 2016, 12:05 a.m.

There is a round(number, ndigits) function for rounding of numbers, where number is required number for rounding, ndigits is a number of simbols after comma. For example:

round(2.137, 2)  # = 2.14

Round function has some feature that consists in the fact that it works on the principle of bank rounding to round off the numbers in which the last five is a sign, for example:

round(2.05, 1)  # = 2.0
round(2.15, 1)  # = 2.1
round(2.25, 1)  # = 2.3
round(2.35, 1)  # = 2.4
round(2.45, 1)  # = 2.5
round(2.55, 1)  # = 2.5
round(2.65, 1)  # = 2.6
round(2.75, 1)  # = 2.8
round(2.85, 1)  # = 2.9
round(2.95, 1)  # = 3.0

Rounding is performed on a special principle. I tell why it is so. Banking (or accounting) rounding allows you to reduce errors when working with a large array of data. Ordinary (or arithmetic) rounding gives an increasing error due to the fact that rounding down should have at the end numbers: 1, 2, 3, 4 - only 4 digits, and in large: 5, 6, 7, 8, 9 - only 5 digits. An uneven number of digits and cause an increasing error in the calculations. A bank rounding works according to statistical laws: the probability that the five will be an even or odd number about the same, so this principle reduces the error.

In python the rounding to ceiling value (to upwards) math.ceil(x) - the smallest integer not less than x.

And the rounding to floor value (to downwards) math.floor(x) - the largest integer not greater than x.

import math

math.ceil(2.3)  # = 3.0
math.floor(2.7)  # = 2.0

For getting a integer number you should use int:

round(2.6)  # = 3.0
int(round(2.6))  # = 3

For getting rid of symbols after comma you can do so:

int(2.6)  # = 2 , is equal to int(math.floor(2.6))

Rate this article

5 from 5 (total 16 ratings)

You can send feedback, suggestions or comments on this article using this form:

Fields marked by star ( * ) is required.

Thank you for yor feedback!

After clicking the "Send" button, your message will be delivered to me on the mail.

Author of Article

Artem Maltsev

Web-developer, having the knowlenge of programming language - Python, framework - Django, content management system - Django CMS, platform of e-commerce site - Django Shop and many other applications, using this technologies.

The right to use content on this page https://vivazzi.pro/it/round-python/:

Permission is granted to copy an content with its author and reference to the original without using the parameter rel="nofollow" in tag <a>. Usage:

Author of Article: Artem Maltsev
Link to article: <a href="https://vivazzi.pro/it/round-python/">https://vivazzi.pro/it/round-python/</a>

More: Terms of site usage

Related Posts:

Comments: 8

Гость
Гость

26.02.2018 9:14 #

Заблуждение ! В python обычное математическое округление. Описанное поведение связано с неточностью представления десятичных чисел во float .

>>> '%0.30f' % 2.45
'2.450000000000000177635683940025'
>>> '%0.30f' % 2.55
'2.549999999999999822364316059975'

Reply

Артём Мальцев
Артём Мальцев author

27.02.2018 4:17 #

Гость, спасибо за ваш комментарий!
Миф о банковском округлении разрушен, статью подправил.
Обновлено 10.06.2018: Нет, миф всё-таки не разрушен, см. комментарии ниже https://vivazzi.pro/it/round-python/#comment_154

Reply

Дмитрий
Дмитрий

09.06.2018 21:16 #

В python3 именно банковское округление. Но и неточности float тоже присутствуют.
Если Вы считаете что в python3 арифметическое округление, то объясните пожалуйста это:

>>> round(2.5)
2
>>> '%0.100f' % 2.5
'2.5000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
>>>

Reply

Артём Мальцев
Артём Мальцев author

10.06.2018 4:01 #

Да, согласен в python 2 и python 3 в примере round(2.5) дают разные результаты (2 и 3 соответственно) .

Хорошо, Дмитрий, приведите, пожалуйста, официальные источники, как всё-таки идёт округление в python. Пока из авторитетных источников я нашёл только это https://docs.python.org/2/library/functions.html#round (для python 2) и https://docs.python.org/3/library/functions.html#round (для python 3) - и в них не говорится о банковском округлении.

Reply

Дмитрий
Дмитрий

11.06.2018 6:56 #

Собственно в py3 документации по Вашей ссылке об этом и сказано :

if two multiples are equally close, rounding is done toward the even choic e Округление делается до ближайшего четного - это и есть банковское округление . P.S. Чтобы выяснить, какое округление используется, нужно брать числа, которые не имеют неточностей и стоят ровно между двух чисел. Тогда начинает работать правило: либо это арифметическое (py2) - округляем вверх, либо это банковское (py3) - округляем до ближайшего четного. А если число не стоит ровно между двух чисел (например имеет неточности float), то и в py2 и в py3 работает простое правило - округляем до ближайшего числа.

Reply

Артём Мальцев
Артём Мальцев author

11.06.2018 11:26 #

Дмитрий, большое спасибо за подробное объяснение, как всё-таки идёт округление в python!

Reply

Гость
Гость

22.12.2020 22:47 #

Очень жаль, что в банках (российских?) не используется "банковское округление". Приходится писать собственные функции округления, что нонсенс для такого продвинутого языка.

Reply

Артём Мальцев
Артём Мальцев author

24.12.2020 10:17 #

Это весьма странно, что в каких-то российских банках не используется банковское округление. Ведь этому, как я понимаю, ещё в университетах учат на экономических специальностях . Видимо, некоторые банки хотят побольше насобирать копеек, ведь проведя миллионы операций будет весьма ощутимая разница. Я даже приводил пример в нашем проекте https://vivazzi.pro/viva-tm/advantages/#11-tochnost-vychisleni y По хорошему надо обратиться в руководство банка с требованием изменить логику округления чисел в пользу банковского округления.

Reply

You can leave a comment as an unregistered user.

But if you sing up, you can:

  • receive notifications
  • view your comments
  • be able to use all the functions of the developed services

To comment in one's own name you should log in or sign up on Vuspace website

Send

There is no search on this site, so I offer to use usual search engine, for example, Google, adding "vivazzi" after your request.

Try it

Select currency for displaying monetary values