簡體   English   中英

Python方式將浮點數舍入到特定的最小和最大小數位數

[英]Pythonic way to round a float to specific min AND max number of decimal places

我想實現一個函數round(num, min, max) ,該函數將浮點數至少round(num, min, max)min小數位和max 我希望它返回一個字符串。 我有一些有效的方法,但是時間太長了。 你能寫比我更pythonic的東西嗎?

用法

round(3.14159, 2, 4) --> '3.1416'
round(3.14159, 0, 2) --> '3.14'
round(3.14159, 0, 1) --> '3.1'
round(3.14159, 0, 0) --> '3'
round(3.14159, 4, 6) --> '3.141590'
round(3.14, 4, 6)    --> '3.1400'
round(3, 4, 6)       --> '3.0000'

我想你應該已經明白了。 這就是我所擁有的。

def normalize(amount, min=0, max=2):
    """
    Rounds to a variable number of decimal places - as few as necessary in the range [min,max]
    :param amount: A float, int, decimal.Decimal, or string.
    :param min: the minimum number of decimal places to keep
    :param max: the maximum number of decimal places to keep
    :return: string.
    """
    if not amount:
        return amount

    # To Decimal, round to highest desired precision
    d = round(Decimal(amount), max)
    s = str(d)

    # Truncate as many extra zeros as we are allowed to
    for i in range(max-min):
        if s[-1] == '0':
            s = s[:-1]

    # Lose a trailing decimal point.
    if s[-1] == '.':
        s = s[:-1]

    return s

您將浮點數舍入與打印格式混淆。 *

浮點數3.143.1415不同。 因此,將3.1415舍入到2位數字是有意義的。

但是float 3.003.0完全相同。 因此,將3.0舍入到2位數將無濟於事。 它仍然與開始時一樣。

同時,如果要更改數字的打印方式,可以使用format函數, str.format方法,f字符串, %格式設置等來完成。例如:

>>> pi = 3.1415
>>> indianapi = round(pi, 0)
>>> indianapi
3.0
>>> f'{indianapi:.3f}'
'3.000'

格式化規范的迷你語言有關如何使用F-字符串(和細節str.formatformat ),以及printf風格的字符串格式化有關如何使用細節%


*或者,或者您期望float跟蹤其精度並通過一系列操作來保持精度。 如果那是您想要的,則浮點數不能做到這一點,而decimal.Decimal可以。 decimal可以,因此您可能需要查看decimal模塊。 但我認為這不是您想要的。

只是一些小的改進,但保持基本思路(轉換價值,帶零,帶尾隨小數點)。

第一個更改是避免使用內置函數minmax發生名稱沖突。 我認為,使用專為特定目的的功能( str.format的價值格式化, str.rstrip從右側剝離, str.endswith用於測試的最后一個字符),使得它有點更Python。

def round(amount, dmin, dmax):
    assert 0 <= dmin <= dmax
    astr = '{:.{prec}f}'.format(amount, prec=dmax)
    if dmax != dmin:
        astr = astr[:dmin-dmax] + astr[dmin-dmax:].rstrip('0')
        if astr.endswith('.'):
            astr = astr[:-1]
    return astr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM