python 2 中是否有可以執行此操作的函數?1234 -> round(1234, 2) = 12001234 -> round(1234, 3) = 123012.34 -> round(12.34, 3) = 12.3基本上第二個數字表示數字的精度,后面的所有內容都應該四舍五入。根據評論我想出了這個:def round_to_precision(x, precision): return int(round(x / float(10 ** precision))) * 10 ** precision但這仍然是錯誤的,因為我不知道數字的大小。
2 回答

阿晨1998
TA貢獻2037條經驗 獲得超6個贊
這是一個解決方案(為清楚起見,逐步編寫)。
import math
num_digits = lambda x: int((math.log(x, 10)) + 1)
def round(x, precision):
digits = num_digits(x)
gap = precision - digits
x = x * (10 ** gap)
x = int(x)
x = x / (10 ** gap)
return x
結果:
round(1234, 2) # 1200
round(1234, 3) # 1230
round(12.34, 3) # 12.3

繁花如伊
TA貢獻2012條經驗 獲得超12個贊
我找到了一個解決方案:
def round_to_precision(x, precision):
fmt_string = '{:.' + str(precision) + 'g}'
return float(fmt_string.format(x))
print round_to_precision(1234, 2)
print round_to_precision(1234, 3)
print round_to_precision(12.34, 3)
添加回答
舉報
0/150
提交
取消