![](/img/trans.png)
[英]Round to 3 decimal places if needed otherwise round to 2 decimal places in Pythonic manner
[英]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.14
與3.1415
不同。 因此,將3.1415
舍入到2位數字是有意義的。
但是float 3.00
與3.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.format
和format
),以及printf
風格的字符串格式化有關如何使用細節%
。
*或者,或者您期望float跟蹤其精度並通過一系列操作來保持精度。 如果那是您想要的,則浮點數不能做到這一點,而decimal.Decimal
可以。 decimal
可以,因此您可能需要查看decimal
模塊。 但我認為這不是您想要的。
只是一些小的改進,但保持基本思路(轉換價值,帶零,帶尾隨小數點)。
第一個更改是避免使用內置函數min
和max
發生名稱沖突。 我認為,使用專為特定目的的功能( 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.