Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python小数点后保留两位小数

作者:凌傲天   发布日期:2025-10-15   浏览:69

# 示例代码:保留小数点后两位小数

# 方法1:使用 round() 函数
num = 3.14159
rounded_num = round(num, 2)
print(f"使用 round() 函数: {rounded_num}")  # 输出: 使用 round() 函数: 3.14

# 方法2:使用格式化字符串
num = 3.14159
formatted_num = "{:.2f}".format(num)
print(f"使用格式化字符串: {formatted_num}")  # 输出: 使用格式化字符串: 3.14

# 方法3:使用 f-string (Python 3.6+)
num = 3.14159
f_string_num = f"{num:.2f}"
print(f"使用 f-string: {f_string_num}")  # 输出: 使用 f-string: 3.14

解释说明:

  1. round() 函数round(num, 2) 将数字 num 保留到小数点后两位。注意,round() 可能会进行四舍五入。
  2. 格式化字符串"{:.2f}".format(num) 使用格式化字符串将数字保留两位小数,.2f 表示保留两位小数的浮点数。
  3. f-stringf"{num:.2f}" 是 Python 3.6 引入的 f-string 语法,同样可以实现保留两位小数的效果。

以上三种方法都可以实现保留小数点后两位小数的功能,你可以根据具体需求选择合适的方法。

上一篇:python获取当前日期

下一篇:python 读取json

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站