亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python固定數字舍入

python固定數字舍入

MM們 2022-12-20 14:26:44
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


查看完整回答
反對 回復 2022-12-20
?
繁花如伊

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)


查看完整回答
反對 回復 2022-12-20
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號