Python打印浮点数保留9位小数失败,round函数无效如何解决
Python复利计算程序小数位数显示问题修复方案
问题根因
你遇到的输出小数位数超长的问题来自两个错误写法:
compound_one_account函数的打印语句没有指定浮点数输出格式,Python默认会输出float类型的全部有效数位,导致出现上百位小数的情况compound_two_account函数中{total_account_value,9}的写法完全错误,该语法会将数值和9打包为元组输出,完全达不到保留9位小数的效果
修复方法
Python f-string中浮点数固定保留n位小数的标准语法为 {变量:.9f},该格式化逻辑会自动完成四舍五入,不需要额外调用round函数即可实现保留9位小数的输出需求。
如果需要在计算过程中就对数值做舍入存储,可以在更新账户金额时调用round函数,写法为:account_value = round(apply_interest(account_value, interest_rate), 9)
修正后完整代码
import math def apply_interest(original_amount: float, interest_rate: float) -> float: return original_amount * (1.0 + interest_rate) def compound_one_account(account_value: float, interest_rate: float, days: int) -> float: for day in range(days): # 新增格式化规则,保留9位小数 print(f"Value is {account_value:.9f} on day {day}") account_value = apply_interest(account_value, interest_rate) def compound_two_account(account_value: float, account_value2: float, interest_rate: float, days: int) -> float: total_account_value = account_value + account_value2 for day in range(days): # 修正错误的格式化写法,使用标准的浮点数小数位控制语法 print(f"Value is {total_account_value:.9f} on day {day}") total_account_value = apply_interest(total_account_value, interest_rate) compound_one_account(5000, 0.025, 5) compound_two_account(2500, 2500, 0.025, 5)
可选优化(针对高精度金融计算场景)
如果你的复利计算对精度要求极高,不希望出现float类型的二进制精度丢失问题,可以替换为Python标准库的decimal模块做精确十进制计算,示例用法如下:
from decimal import Decimal, getcontext # 全局设置Decimal计算精度为20位,足够覆盖9位小数的输出需求 getcontext().prec = 20 def apply_interest(original_amount: Decimal, interest_rate: Decimal) -> Decimal: return original_amount * (Decimal('1') + interest_rate)
内容的提问来源于stack exchange,提问作者Jeremiah Dunphy
相关产品推荐
相关产品推荐

