如何将浮点数舍入到某个小数位?

时间:2022-02-27 16:30:42

Suppose I am having 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.

假设我有8.8333333333333339并且我想将其转换为8.84,我怎样才能在python中完成此操作? round(8.8333333333333339,2)给出8.83而不是8.84。我是python或编程的新手。

I don't want to print it as a string, the result will be further used. For more information on the problem please check Tim Wilson's Python Programming Tips: Loan and payment calculator.

我不想将其打印为字符串,结果将被进一步使用。有关该问题的更多信息,请查看Tim Wilson的Python编程技巧:贷款和付款计算器。

11 个解决方案

#1


90  

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:

8.833333333339(或8.833333333333334,结果为106.00 / 12)正确舍入到两位小数是8.83。在数学上,它听起来像你想要的是天花板功能。 Python的数学模块中的一个名为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 102 (or 100) to shift the decimal point and is then divided by it afterwards to compensate.

地板和天花板功能通常将实数映射到具有零小数位的最大前一个或最小的后续整数 - 因此要将它们用于2个小数位数,首先将该数字乘以102(或100)以移动小数点然后由它分开以进行补偿。

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 <= n else n+1

How this applies to the linked loan and payment calculator problem

如何将浮点数舍入到某个小数位?

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 112 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.

从示例输出看来,它们会将每月付款进行四舍五入,这就是许多人称之为上限功能的效果。这意味着每月支付的金额略高于总金额的1/12。这使得最终付款比平时略小 - 剩余的未付余额仅为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.

使用正常的舍入产生每月支付8.83和稍高的最终支付8.87同样有效。然而,在现实世界中,人们通常不喜欢将他们的付款上涨,因此将每笔付款四舍五入是通常的做法 - 它还会更快地将钱返还给贷方。

#2


57  

This is normal (and has nothing to do with Python) because 8.83 cannot be represented exactly as a binary float, just as 1/3 cannot be represented exactly in decimal (0.333333... ad infinitum).

这是正常的(并且与Python无关)因为8.83不能完全表示为二进制浮点数,正如1/3不能精确地用十进制表示(0.333333 ... ad infinitum)。

If you want to ensure absolute precision, you need the decimal module:

如果要确保绝对精度,则需要十进制模块:

>>> import decimal
>>> a = decimal.Decimal("8.833333333339")
>>> print(round(a,2))
8.83

#3


19  

You want to use the decimal module but you also need to specify the rounding mode. Here's an example:

您想使用十进制模块,但您还需要指定舍入模式。这是一个例子:

>>> import decimal
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP)
Decimal('8.34')
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
Decimal('8.33')
>>> 

#4


9  

A much simpler way is to simply use the round() function. Here is an example.

一种更简单的方法是简单地使用round()函数。这是一个例子。

total_price = float()
price_1 = 2.99
price_2 = 0.99
total_price = price_1 + price_2

If you were to print out total_price right now you would get

如果你现在要打印出total_price,你就会得到

3.9800000000000004

But if you enclose it in a round() function like so

但是如果你将它括在round()函数中就好了

print(round(total_price,2))

The output equals

输出等于

3.98

The round() function works by accepting two parameters. The first is the number you want to round. The second is the number of decimal places to round to.

round()函数通过接受两个参数来工作。第一个是您要舍入的数字。第二个是要舍入的小数位数。

#5


7  

If you round 8.8333333333339 to 2 decimals, the correct answer is 8.83, not 8.84. The reason you got 8.83000000001 is because 8.83 is a number that cannot be correctly reprecented in binary, and it gives you the closest one. If you want to print it without all the zeros, do as VGE says:

如果您将8.8333333333339舍入为2位小数,则正确答案为8.83,而不是8.84。你得到8.83000000001的原因是8.83是一个无法用二进制正确表示的数字,它给你最接近的数字。如果你想在没有全零的情况下进行打印,请按照VGE的说法进行操作:

print "%.2f" % 8.833333333339   #(Replace number with the variable?)

#6


5  

If you want to round, 8.84 is the incorrect answer. 8.833333333333 rounded is 8.83 not 8.84. If you want to always round up, then you can use math.ceil. Do both in a combination with string formatting, because rounding a float number itself doesn't make sense.

如果你想圆,8.84是不正确的答案。 8.833333333333舍入为8.83而不是8.84。如果你想总是向上舍入,那么你可以使用math.ceil。两者都与字符串格式组合,因为舍入浮点数本身没有意义。

"%.2f" % (math.ceil(x * 100) / 100)

#7


3  

Just for the record. You could do it this way:

只是为了记录。你可以这样做:

def roundno(no):
    return int(no//1 + ((no%1)/0.5)//1)

There, no need for includes/imports

在那里,不需要包含/导入

#8


1  

use the decimal module: http://docs.python.org/library/decimal.html

使用十进制模块:http://docs.python.org/library/decimal.html

#9


1  

Hier is my solution for the round up/down problem

Hier是我解决上下行问题的解决方案

< .5 round down

<.5向下舍入

> = .5 round up

import math

def _should_round_down(val: float):
    if val < 0:
        return ((val * -1) % 1) < 0.5
    return (val % 1) < 0.5

def _round(val: float, ndigits=0):
    if ndigits > 0:
        val *= 10 ** (ndigits - 1)

    is_positive = val > 0
    tmp_val = val
    if not is_positive:
        tmp_val *= -1

    rounded_value = math.floor(tmp_val) if _should_round_down(val) else    math.ceil(tmp_val)
    if not is_positive:
        rounded_value *= -1

    if ndigits > 0:
        rounded_value /= 10 ** (ndigits - 1)

    return rounded_value

# test
# nr = 12.2548
# for digit in range(0, 4):
#     print("{} decimals : {} -> {}".format(digit, nr, _round(nr, digit)))

# output
# 0 decimals : 12.2548 -> 12
# 1 decimals : 12.2548 -> 12.0
# 2 decimals : 12.2548 -> 12.3
# 3 decimals : 12.2548 -> 12.25

#10


1  

The easiest way to do this is by using the below function, which is inbuilt

最简单的方法是使用内置的以下功能

format()

for example:

例如:

format(1.242563,".2f")

the output would be:

输出将是:

1.24

similarly:

类似的:

format(9.165654,".1f")

would give:

会给:

9.2

#11


0  

Here is a simple function to do this for you ::

这是一个为您完成此操作的简单功能::

def precision(num,x):
    return "{0:.xf}".format(round(num))

Here , num is the decimal number x is the decimal upto where you want to round a floating number

这里,num是十进制数x是要对浮点数进行舍入的十进制数

Advantage over other implementation is that it can fill zeros at right end of the decimal to make a deciaml number upto x decimal places .

优于其他实现的是它可以在十进制的右端填充零以使十六进制的十进制数。

Example 1:

例1:

precision(10.2,9)

will return 10.200000000 (upto 9 dp )

将返回10.200000000(最多9 dp)

Example 2:

例2:

precision(10.2231,2)

will return 10.22 (upto 2 dp )

将返回10.22(最多2 dp)

#1


90  

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:

8.833333333339(或8.833333333333334,结果为106.00 / 12)正确舍入到两位小数是8.83。在数学上,它听起来像你想要的是天花板功能。 Python的数学模块中的一个名为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 102 (or 100) to shift the decimal point and is then divided by it afterwards to compensate.

地板和天花板功能通常将实数映射到具有零小数位的最大前一个或最小的后续整数 - 因此要将它们用于2个小数位数,首先将该数字乘以102(或100)以移动小数点然后由它分开以进行补偿。

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 <= n else n+1

How this applies to the linked loan and payment calculator problem

如何将浮点数舍入到某个小数位?

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 112 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.

从示例输出看来,它们会将每月付款进行四舍五入,这就是许多人称之为上限功能的效果。这意味着每月支付的金额略高于总金额的1/12。这使得最终付款比平时略小 - 剩余的未付余额仅为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.

使用正常的舍入产生每月支付8.83和稍高的最终支付8.87同样有效。然而,在现实世界中,人们通常不喜欢将他们的付款上涨,因此将每笔付款四舍五入是通常的做法 - 它还会更快地将钱返还给贷方。

#2


57  

This is normal (and has nothing to do with Python) because 8.83 cannot be represented exactly as a binary float, just as 1/3 cannot be represented exactly in decimal (0.333333... ad infinitum).

这是正常的(并且与Python无关)因为8.83不能完全表示为二进制浮点数,正如1/3不能精确地用十进制表示(0.333333 ... ad infinitum)。

If you want to ensure absolute precision, you need the decimal module:

如果要确保绝对精度,则需要十进制模块:

>>> import decimal
>>> a = decimal.Decimal("8.833333333339")
>>> print(round(a,2))
8.83

#3


19  

You want to use the decimal module but you also need to specify the rounding mode. Here's an example:

您想使用十进制模块,但您还需要指定舍入模式。这是一个例子:

>>> import decimal
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP)
Decimal('8.34')
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
Decimal('8.33')
>>> 

#4


9  

A much simpler way is to simply use the round() function. Here is an example.

一种更简单的方法是简单地使用round()函数。这是一个例子。

total_price = float()
price_1 = 2.99
price_2 = 0.99
total_price = price_1 + price_2

If you were to print out total_price right now you would get

如果你现在要打印出total_price,你就会得到

3.9800000000000004

But if you enclose it in a round() function like so

但是如果你将它括在round()函数中就好了

print(round(total_price,2))

The output equals

输出等于

3.98

The round() function works by accepting two parameters. The first is the number you want to round. The second is the number of decimal places to round to.

round()函数通过接受两个参数来工作。第一个是您要舍入的数字。第二个是要舍入的小数位数。

#5


7  

If you round 8.8333333333339 to 2 decimals, the correct answer is 8.83, not 8.84. The reason you got 8.83000000001 is because 8.83 is a number that cannot be correctly reprecented in binary, and it gives you the closest one. If you want to print it without all the zeros, do as VGE says:

如果您将8.8333333333339舍入为2位小数,则正确答案为8.83,而不是8.84。你得到8.83000000001的原因是8.83是一个无法用二进制正确表示的数字,它给你最接近的数字。如果你想在没有全零的情况下进行打印,请按照VGE的说法进行操作:

print "%.2f" % 8.833333333339   #(Replace number with the variable?)

#6


5  

If you want to round, 8.84 is the incorrect answer. 8.833333333333 rounded is 8.83 not 8.84. If you want to always round up, then you can use math.ceil. Do both in a combination with string formatting, because rounding a float number itself doesn't make sense.

如果你想圆,8.84是不正确的答案。 8.833333333333舍入为8.83而不是8.84。如果你想总是向上舍入,那么你可以使用math.ceil。两者都与字符串格式组合,因为舍入浮点数本身没有意义。

"%.2f" % (math.ceil(x * 100) / 100)

#7


3  

Just for the record. You could do it this way:

只是为了记录。你可以这样做:

def roundno(no):
    return int(no//1 + ((no%1)/0.5)//1)

There, no need for includes/imports

在那里,不需要包含/导入

#8


1  

use the decimal module: http://docs.python.org/library/decimal.html

使用十进制模块:http://docs.python.org/library/decimal.html

#9


1  

Hier is my solution for the round up/down problem

Hier是我解决上下行问题的解决方案

< .5 round down

<.5向下舍入

> = .5 round up

import math

def _should_round_down(val: float):
    if val < 0:
        return ((val * -1) % 1) < 0.5
    return (val % 1) < 0.5

def _round(val: float, ndigits=0):
    if ndigits > 0:
        val *= 10 ** (ndigits - 1)

    is_positive = val > 0
    tmp_val = val
    if not is_positive:
        tmp_val *= -1

    rounded_value = math.floor(tmp_val) if _should_round_down(val) else    math.ceil(tmp_val)
    if not is_positive:
        rounded_value *= -1

    if ndigits > 0:
        rounded_value /= 10 ** (ndigits - 1)

    return rounded_value

# test
# nr = 12.2548
# for digit in range(0, 4):
#     print("{} decimals : {} -> {}".format(digit, nr, _round(nr, digit)))

# output
# 0 decimals : 12.2548 -> 12
# 1 decimals : 12.2548 -> 12.0
# 2 decimals : 12.2548 -> 12.3
# 3 decimals : 12.2548 -> 12.25

#10


1  

The easiest way to do this is by using the below function, which is inbuilt

最简单的方法是使用内置的以下功能

format()

for example:

例如:

format(1.242563,".2f")

the output would be:

输出将是:

1.24

similarly:

类似的:

format(9.165654,".1f")

would give:

会给:

9.2

#11


0  

Here is a simple function to do this for you ::

这是一个为您完成此操作的简单功能::

def precision(num,x):
    return "{0:.xf}".format(round(num))

Here , num is the decimal number x is the decimal upto where you want to round a floating number

这里,num是十进制数x是要对浮点数进行舍入的十进制数

Advantage over other implementation is that it can fill zeros at right end of the decimal to make a deciaml number upto x decimal places .

优于其他实现的是它可以在十进制的右端填充零以使十六进制的十进制数。

Example 1:

例1:

precision(10.2,9)

will return 10.200000000 (upto 9 dp )

将返回10.200000000(最多9 dp)

Example 2:

例2:

precision(10.2231,2)

will return 10.22 (upto 2 dp )

将返回10.22(最多2 dp)