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

如何将Python脚本中BMP180传感器的海拔输出格式化为两位小数

解决BMP180海拔值保留两位小数插入MySQL的问题

有两种简单直接的方法可以实现需求,以下是具体修改方案:

方法1:使用round()函数进行数值四舍五入

round()函数可直接将数值四舍五入到指定小数位,适合数据库字段为数值类型(如DECIMAL(8,2)、FLOAT)的场景:

修改代码中插入数据库的执行语句:

cursor.execute("insert into weather_data(temperature_celsius, pressure_hPa, altitude_meters, date, time) values(%s,%s,%s,%s,%s)", 
               (t.C, p.hPa, round(a.m, 2), date, time))
  • 移除了不必要的str()转换,mysql.connector会自动处理数值类型参数,避免字符串转数值的潜在问题
  • round(a.m, 2)会把海拔值a.m四舍五入为两位小数的数值

方法2:使用字符串格式化输出固定小数位

如果需要生成格式化后的字符串(比如数据库字段为字符串类型),可以用字符串格式化语法:

修改插入语句:

cursor.execute("insert into weather_data(temperature_celsius, pressure_hPa, altitude_meters, date, time) values(%s,%s,%s,%s,%s)", 
               (str(t.C), str(p.hPa), "{:.2f}".format(a.m), date, time))
  • "{:.2f}".format(a.m)会生成固定两位小数的字符串,例如将286.4581156518178转换为"286.46"

额外优化建议

  • 建议将数据库中temperature_celsius、pressure_hPa、altitude_meters字段设置为数值类型(如DECIMAL(6,2)),而非字符串类型,更利于后续的数据统计、计算和排序
  • 可同步优化温度和气压的输出格式,比如用round(t.C, 1)或"{:.1f}".format(t.C)统一格式

修改后的完整代码片段(以方法1为例):

try:
    # Insert into the database
    cursor.execute("insert into weather_data(temperature_celsius, pressure_hPa, altitude_meters, date, time) values(%s,%s,%s,%s,%s)", 
                   (t.C, p.hPa, round(a.m, 2), date, time))
    # Commit the changes
    db.commit()
    cursor.close()
    db.close()
# Handle exceptions
except Exception as error:
    print("error: There was a problem inserting data in the database")
    print(error)
    # Rollback db transaction
    db.rollback()
    # Close the database object
    db.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:45:52