Python 中四舍五入到小数点后 2 位

发布于 2025-01-17 22:32:32 字数 519 浏览 0 评论 0原文

我有一个初学者问题。我该如何汇总2个小数? 这是我尝试的和我想实现的目标:

import math

var_1 = 14.063  # expected = 14.06
var_2 = 10.625  # expected = 10.63

print(round(14.063, 2))
print(round(10.625, 2))


print('===========================')


def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier


print(round_up(var_1, 2))
print(round_up(var_2, 2))

输出是:

14.06 
10.62  
===========================
14.07
10.63

所以这些都不适合我...

I have a beginner problem. How can I round up to 2 decimal?
Here is what I tried and what I want to achieve:

import math

var_1 = 14.063  # expected = 14.06
var_2 = 10.625  # expected = 10.63

print(round(14.063, 2))
print(round(10.625, 2))


print('===========================')


def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier


print(round_up(var_1, 2))
print(round_up(var_2, 2))

And the Output is:

14.06 
10.62  
===========================
14.07
10.63

So neither of those wroks for me...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

若水般的淡然安静女子 2025-01-24 22:32:32

十进制模块的小数类,量化()方法和round_half_up规则可以处理这一点:

from decimal import Decimal, ROUND_HALF_UP

var_1 = 14.063  # expected = 14.06
var_2 = 10.625  # expected = 10.63

# a Decimal object with an explicit exponent attribute/property (to be interpreted by quantize)
Two_places = Decimal("1e-2")

for var in [var_1, var_2]:
    rounded = Decimal(var).quantize(Two_places, rounding=ROUND_HALF_UP)
    print(f"decimal: {rounded}")
    print(f"float:   {float(rounded)}")

我得到:

decimal: 14.06
float:   14.06
decimal: 10.63
float:   10.63

请记住,当您处理浮子时,您总是在操纵对什么比不太明确的表示什么您可能(自然地)想到了:

Decimal(1.65)    # Decimal('1.649999999999999911182158029987476766109466552734375')
Decimal('1.65')  # Decimal('1.65')

在第一种情况下,首先将1.65变成IEEE-754浮点,该浮点具有从Base-10到Base-2的精度错误,然后传递到十进制。在第二种情况下,十进制将数字解释为“一个和65个100-1”,相当于“ 165乘以10升至负2”或165E-2。

The Decimal class, quantize() method, and ROUND_HALF_UP rule from the decimal module can handle this:

from decimal import Decimal, ROUND_HALF_UP

var_1 = 14.063  # expected = 14.06
var_2 = 10.625  # expected = 10.63

# a Decimal object with an explicit exponent attribute/property (to be interpreted by quantize)
Two_places = Decimal("1e-2")

for var in [var_1, var_2]:
    rounded = Decimal(var).quantize(Two_places, rounding=ROUND_HALF_UP)
    print(f"decimal: {rounded}")
    print(f"float:   {float(rounded)}")

and I get:

decimal: 14.06
float:   14.06
decimal: 10.63
float:   10.63

Keep in mind that when you're dealing with floats, you're always manipulating a less-than-precise representation of what you probably (naturally) have in mind:

Decimal(1.65)    # Decimal('1.649999999999999911182158029987476766109466552734375')
Decimal('1.65')  # Decimal('1.65')

In the first case, 1.65 was first turned into an IEEE-754 float, which has precision errors going from base-10 to base-2, then passed to Decimal. In the second case, Decimal interpreted the number as "one, and 65 100-ths" which equates to "165 times 10 raised to the minus 2", or 165e-2.

娇纵 2025-01-24 22:32:32

试试这个。这会找到最近的一个,如果没有,则向上舍入 -

import math
v1 = 14.063
v2 = 10.625

def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    var_down = round(n, 2)
    var_up = math.ceil(n * multiplier) / multiplier

    if n - var_down >= var_up - n:
        return var_up

    else:
        return var_down

v1_round = round_up(v1, 2)
v2_round = round_up(v2, 2)

print (v1_round) # 14.06
print (v2_round) # 10.63

Try this. This finds the nearest one and if not, then round up -

import math
v1 = 14.063
v2 = 10.625

def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    var_down = round(n, 2)
    var_up = math.ceil(n * multiplier) / multiplier

    if n - var_down >= var_up - n:
        return var_up

    else:
        return var_down

v1_round = round_up(v1, 2)
v2_round = round_up(v2, 2)

print (v1_round) # 14.06
print (v2_round) # 10.63
沩ん囻菔务 2025-01-24 22:32:32

这应该有效,尽管有一种更有效的方法的方法。我只是拿走了您的代码,并确定了哪一个距离更接近,如果它们相同。
编辑:PCM似乎已经制作了这样的版本。

import math
decimals = 2
var_1 = 14.063
var_2 = 10.625

var_1down = round(var_1, decimals)
var_2down = round(var_2, decimals)

def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

var_1up = round_up(var_1, decimals)
var_2up = round_up(var_2, decimals)

if var_1 - var_1down >= var_1up - var_1:
    var_1round = var_1up
else:
    var_1round = var_1down

if var_2 - var_2down >= var_2up - var_2:
    var_2round = var_2up
else:
    var_2round = var_2down

print (var_1round)
print (var_2round)

this should work, although there is probebly a more efficient way of doing it. I just took your code and determined which one was closer, and if they are the same to round up.
Edit: It seems that PCM has made such version.

import math
decimals = 2
var_1 = 14.063
var_2 = 10.625

var_1down = round(var_1, decimals)
var_2down = round(var_2, decimals)

def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

var_1up = round_up(var_1, decimals)
var_2up = round_up(var_2, decimals)

if var_1 - var_1down >= var_1up - var_1:
    var_1round = var_1up
else:
    var_1round = var_1down

if var_2 - var_2down >= var_2up - var_2:
    var_2round = var_2up
else:
    var_2round = var_2down

print (var_1round)
print (var_2round)
伊面 2025-01-24 22:32:32

如果您检查文档,您会看到“值将圆形到最接近的倍数到10的最接近元素,如果两个倍数同样接近,则圆形对偶数选择进行(例如,例如,两个圆形(0.5)(0.5)(0.5)圆(-0.5)为0,圆(1.5)为2)”。

因此,10.625回合至10.62。您可以尝试添加一个很小的值,例如0.00001,但即使如此,由于浮点数的工作方式,在少数情况下,您可能会感到惊讶。

If you check the docs you will see that "values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)".

So 10.625 rounds to 10.62. You may try adding a very small value, e.g. 0.00001, but even so, since the way float numbers work, you may have some surprise in a few cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文