python中浮点数精度处理_更改浮点的精度并在Python中存储

我到处寻找这个问题的答案,只找到了我问题的一部分。

我在整个过程中对代码进行了注释,以说明哪些是有效的,哪些是无效的,以及

每一行都有多大的错误。提前谢谢。在#

# list_of_numbers is a list with numbers

# like '3.543345354'

#

# I want to change to a number with two places

#

#

# for each item in the list

for idx, value in enumerate(list_of_numbers):

# make sure it is not none

if value != None:

#

# convert to a float - this works

temp_val = float(value)

# test and print the format - yep this works

print("%.2f" % temp_val)

# store in a new variable - works

formatted_number = "%.2f" % temp_val

# check - yep looks good so far. the line blow will print 3.54 etc

print formatted_number

#

# now try to store it back

#

# the below two lines when I try both give me the

# unsupported operand type(s) for +: 'float' and 'str'error

list_of_numbers[idx] = formatted_number

list_of_numbers[idx] = '%s' % formatted_number

#

# the line below give me the error

# float argument required, not str

list_of_numbers[idx] = '%f' % formatted_number

#

# so from the above error formatted_number is a string.

# so why cant I set the variable with the string

#

# the ONLY thing that works is the lone below but I

# dont want an integer

#

list_of_numbers[idx] = int(float(value ))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值