繁体   English   中英

如何确保一个数字被除后总是有 2 位小数?

[英]How to make sure there is always 2 decimal places after a number is divided?

我不知道怎么做,这样当我除以5 / 2之类的东西时,它后面不仅有 1 个小数位,例如,它提供的答案不是2.5 ,而是我想要的返回2.50 有什么方法可以做到这一点而不必导入库? 如果没有一个好的和有效的方法,那么有人能指出我应该从哪里开始阅读如何做到这一点的正确方向吗?

您可能应该导入decimal模块并使用它:

import decimal

# you can use a string "2.50"
print(decimal.Decimal("2.50")) 

# or you can use a float 2.5
print(decimal.Decimal(2.5).quantize(decimal.Decimal("0.01")))


# if your float has lots of decimal places it will round up (not floor)
print(decimal.Decimal(2.556).quantize(decimal.Decimal("0.01"))) 

以下是文档: https://docs.python.org/3.10/library/decimal.html

您也可以使用“字符串格式”将其作为字符串获取:

print('{:.2f}'.format(2.5))

以下是相关文档: https://docs.python.org/3/library/string.html#format-specification-mini-language

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM