You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用math.floor函数时如何保留两位小数(示例输出:1.00)

解决math.floor结果保留两位小数的问题

math.floor() 函数返回的是整数类型,要让输出保留两位小数(比如1.00),只需要把它的计算结果传入格式化语句即可,有两种常用写法:

  • 方法一:使用str.format()

    import math
    print("{:.2f}".format(math.floor(1.4)))
    

    执行后会输出 1.00,原理是先通过math.floor(1.4)得到整数1,再用格式化规则将其转为带两位小数的字符串。

  • 方法二:使用f-string(Python 3.6及以上版本支持)

    import math
    print(f"{math.floor(1.4):.2f}")
    

    这种写法更简洁,直接在占位符中嵌入math.floor的计算表达式,并指定小数格式。

内容的提问来源于stack exchange,提问作者Kevin longsmith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 09:04:53