Округлить число до тысячных python

Round float to x decimals?

I’ve found ways to trim/truncate them (66.666666666 —> 66.6666), but not round (66.666666666 —> 66.6667).

6 Answers 6

I feel compelled to provide a counterpoint to Ashwini Chaudhary’s answer. Despite appearances, the two-argument form of the round function does not round a Python float to a given number of decimal places, and it’s often not the solution you want, even when you think it is. Let me explain.

The ability to round a (Python) float to some number of decimal places is something that’s frequently requested, but turns out to be rarely what’s actually needed. The beguilingly simple answer round(x, number_of_places) is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it’s doing something rather subtler. Consider the following example:

With a naive understanding of what round does, this looks wrong: surely it should be rounding up to 52.2 rather than down to 52.1 ? To understand why such behaviours can’t be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it’s far from simple.

So here’s what’s really happening in the example above. (deep breath) We’re displaying a decimal representation of the nearest binary floating-point number to the nearest n -digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):

  1. First the numeric literal 52.15 gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47 , or 52.14999999999999857891452847979962825775146484375 .
  2. Internally as the first step of the round operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15 , we end up rounding down and getting a string 52.1 . This explains why we’re getting 52.1 as the final output instead of 52.2 .
  3. Then in the second step of the round operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1 , which is now 7332423143312589 * 2**-47 , or 52.10000000000000142108547152020037174224853515625 .
  4. Finally, as part of Python’s read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1 as the final output.
Читайте также:  Javascript убрать пробелы начале строки

In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That’s due to Python’s choice of repr implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:

>>> x = 15.34509809234 >>> x 15.34509809234 

Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here’s the original example executed in Python 2.6:

>>> round(52.15, 1) 52.200000000000003 

Not only do we round in the opposite direction, getting 52.2 instead of 52.1 , but the displayed value doesn’t even print as 52.2 ! This behaviour has caused numerous reports to the Python bug tracker along the lines of «round is broken!». But it’s not round that’s broken, it’s user expectations. (Okay, okay, round is a little bit broken in Python 2.6, in that it doesn’t use correct rounding.)

Short version: if you’re using two-argument round, and you’re expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you’re asking for trouble.

So enough with the «two-argument round is bad» argument. What should you be using instead? There are a few possibilities, depending on what you’re trying to do.

    If you’re rounding for display purposes, then you don’t want a float result at all; you want a string. In that case the answer is to use string formatting:

>>> format(66.66666666666, '.4f') '66.6667' >>> format(1.29578293, '.6f') '1.295783' 

Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.

>>> Decimal('66.66666666666').quantize(Decimal('1e-4')) Decimal('66.6667') >>> Decimal('1.29578293').quantize(Decimal('1e-6')) Decimal('1.295783') 

Источник

Как округлить число в Python

При работе со значениями с плавающей запятой (числа с дробной частью) в нашей программе на Python нам может понадобиться округлить число в большую или меньшую сторону или до ближайшего целого числа. В этой статье мы рассмотрим встроенные в Python функции, которые позволяют нам округлять числа, и разберем их работу на примерах.

Мы начнем с функции round() . По умолчанию она округляет исходное число до ближайшего целого числа. Мы также разберем, как использовать аргументы данной функции для изменения типа возвращаемого нам результата.

Затем мы поговорим о методах math.ceil() и math.floor() , которые округляют изначальное число в большую и меньшую сторону до ближайшего целого числа. Эти два метода входят во встроенный математический модуль math в Python.

Как округлить число при помощи метода round()

Функция round() округляет число до указанного количества знаков после запятой. Если количество знаков не указано, функция округлит число до ближайшего целого.

Функция round() принимает два аргумента. Её синтаксис выглядит следующим образом:

Первый параметр — number (число) — это исходное число с дробной частью, которое мы хотим округлить.

Второй параметр — decimal_digits — это количество возвращаемых десятичных знаков. Значение по умолчанию — 0.

Давайте рассмотрим пару примеров.

В нашем первом примере мы используем только один параметр — округляемое число number, равное 2,56789.

Когда мы передали числовую переменную в функцию round() , ее значение было округлено до ближайшего целого числа, то есть до 3.

Вот как легко работает данный метод!

Теперь давайте посмотрим, как работает второй параметр.

x = 2.56789 print(round(x, 2)) # 2.57

В этом коде мы добавили в функцию round() второй параметр. А именно — передали значение 2 в качестве параметра decimal_digits . В результате наша функция округлит число до сотых (два знака после запятой).

В выводе мы получим 2,57: исходное число 2,56789 округляется до двух знаков после запятой и получается 2,57.

Давайте рассмотрим ещё один пример, чтобы получше разобраться в работе второго параметра функции round() .

x = 2.56789 print(round(x, 3)) # 2.568

Теперь мы передали в качестве второго параметра число 3 ( decimal_digits = 3 ). В результате получим число, округленное до тысячных (три знака после запятой).

Первоначальное число 2,56789 было округлено до 2,568.

Вот и всё! Просто, не правда ли?

Простой метод math.ceil() позволяет округлить число до целого в большую сторону. Метод принимает только один аргумент — округляемое число. Синтаксис выглядит следующим образом:

К примеру, мы можем использовать ceil() вот так:

import math x = 5.57468465 print(math.ceil(x)) # 6

Скорее всего, вы заметили, что в приведенном выше коде мы сначала импортировали математический модуль с помощью команды import math . Это дает нам доступ ко всем методам, предоставляемым данным модулем.

Далее мы создали переменную x и присвоили ей значение 5,57468465.

Чтобы округлить исходное число х до ближайшего целого числа, мы передали его методу math.ceil() .

Результирующее значение этой операции, как видно из приведенного выше кода, равно 6.

Таким образом, функция ceil() является некой упрощенной версией round() : она просто округляет исходное значение в большую сторону.

Как округлить число до ближайшего целого при помощи метода math.floor()

Метод floor() в некотором смысле обратный методу ceil() : он тоже округляет число до целого, но в меньшую сторону.

Как и в предыдущем примере, чтобы использовать метод math.floor() , мы должны сначала импортировать математический модуль с помощью команды import math .

Вот так выглядит синтаксис метода math.floor() :

Данный метод точно так же принимает лишь один аргумент — исходное число, которое нужно округлить. Однако floor() округляет до целого числа в меньшую сторону. Давайте рассмотрим следующий пример:

import math x = 5.57468465 print(math.floor(x)) # 5

Мы передали методу math.floor() переменную x , в которой хранится число 5,57468465. В результате это число было округлено до 5.

Заключение

Итак, в этой статье мы разобрали, как округлить число в Python. Мы рассказали о трех встроенных в Python функциях, которые позволяют округлять числа.

Первой была функция round() . Она округляет число до ближайшего целого числа. При этом данная функция также принимает и второй параметр, с помощью которого можно указать, до какого знака после запятой нужно округлить число.

Следующий метод — math.ceil() — округляет число до ближайшего целого числа в большую сторону. Третий метод — math.floor() — тоже округляет число до ближайшего целого, но уже в меньшую сторону. Эти два метода доступны при работе с математическим модулем math . Документацию по модулю math можете посмотреть здесь.

Надеемся данная статья была вам полезна! Успехов в написании кода!

Источник

How to round a floating point number up to a certain decimal place?

Suppose I have 8.8333333333333339 , and I want to convert it to 8.84 . How can I accomplish this in Python? round(8.8333333333333339, 2) gives 8.83 and not 8.84 . I am new to Python or programming in general. I don’t want to print it as a string, and the result will be further used. For more information on the problem, please check Tim Wilson’s Python Programming Tips: Loan and payment calculator.

if you want to print the value use a format such as print «%.2f»%8.8333333333333339. this will print the value with 2 digit

12 Answers 12

8.833333333339 (or 8.833333333333334 , the result of 106.00/12 ) properly rounded to two decimal places is 8.83 . Mathematically it sounds like what you want is a ceiling function. The one in Python’s math module is named ceil :

import math v = 8.8333333333333339 print(math.ceil(v*100)/100) # -> 8.84 

Respectively, the floor and ceiling functions generally map a real number to the largest previous or smallest following integer which has zero decimal places — so to use them for 2 decimal places the number is first multiplied by 10 2 (or 100) to shift the decimal point and is then divided by it afterwards to compensate.

If you don’t want to use the math module for some reason, you can use this (minimally tested) implementation I just wrote:

def ceiling(x): n = int(x) return n if n-1 < x  

How all this relates to the linked Loan and payment calculator problem:

screenshot of loan calculator output

From the sample output it appears that they rounded up the monthly payment, which is what many call the effect of the ceiling function. This means that each month a little more than 1 ⁄12 of the total amount is being paid. That made the final payment a little smaller than usual — leaving a remaining unpaid balance of only 8.76 .

It would have been equally valid to use normal rounding producing a monthly payment of 8.83 and a slightly higher final payment of 8.87 . However, in the real world people generally don't like to have their payments go up, so rounding up each payment is the common practice — it also returns the money to the lender more quickly.

Источник

Оцените статью