如何使用python将浮点数四舍五入为固定小数部分

我有一些价格,如 5.35、10.91、15.55,我使用两位小数四舍五入

Price = "{:.2f}".format(Price)

但是我怎样才能使它们基于固定小数 0.50 和 0.90进行舍入并具有

5.50、10.90、15.50

谢谢


泛舟湖上清波郎朗
浏览 184回答 3
3回答

德玛西亚99

import mathdef weird_round(x):    if round(x % 1, 1) >= 0.9:        return math.floor(x) + 0.9    return math.floor(x) + 0.5prices = [5.35, 10.91, 15.55]for price in prices:    text = "{:.2f}".format(weird_round(price))    print(price, '->', text)5.35 -> 5.5010.91 -> 10.9015.55 -> 15.50

红颜莎娜

如果您有带有小数部分的浮点数,您可以使用第一个和第二个示例,其他所有数字(实际上是所有其他类型)您可以使用第三个和第四个。Num 是你的小数部分。x 是你的 0.5,y 是你的 0.9def round(num, x, y) :&nbsp; &nbsp; av = (x+y)/2&nbsp; &nbsp; if num < av :&nbsp; &nbsp; &nbsp; &nbsp; return x&nbsp; &nbsp; return y或者,如果你想传递像 15.98 这样的数字:def round(num, x, y) :&nbsp; &nbsp; av = (x+y)/2&nbsp; &nbsp; if num % 1 < av :&nbsp; &nbsp; &nbsp; &nbsp; return int(num)+x&nbsp; &nbsp; return int(num)+y您可以致电:round(15.98,0.5,0.9)输出:15.9或者类似的东西:def round(number):&nbsp; &nbsp; x=0.5&nbsp; &nbsp; y=0.9&nbsp; &nbsp; if type(number) is float:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; av = (x+y)/2&nbsp; &nbsp; &nbsp; &nbsp; if number % 1 < av :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return int(number)+x&nbsp; &nbsp; &nbsp; &nbsp; return int(number)+y&nbsp; &nbsp; return number所有这些都在四舍五入。如果你想四舍五入,建筑将是:def round(number):&nbsp; &nbsp; x=0.5&nbsp; &nbsp; y=0.9&nbsp; &nbsp; if type(number) is float:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; av = (x+y)/2&nbsp; &nbsp; &nbsp; &nbsp; from builtins import round as rd&nbsp; &nbsp; &nbsp; &nbsp; if rd(number % 1,2 ) < av :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return int (number)+x&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return int (number)+y&nbsp; &nbsp; &nbsp;return number

慕田峪7331174

对于您提供的示例,此函数应该可以解决问题:def fixed_round(number):&nbsp; &nbsp; decimal = number - int(number)&nbsp; &nbsp; if (abs(0.5 - decimal)) < (abs(0.9 - decimal)):&nbsp; &nbsp; &nbsp; &nbsp; return int(number) + 0.50&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return int(number) + 0.90如果您希望它四舍五入为完整数字,在小数点更接近整数而不是 0.5 的情况下,您需要对此进行调整;)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python