改变Float的精度并在Python中存储

时间:2011-09-20 17:15:51

标签: python floating-point

我一直在寻找答案,只发现了我的问题。 我通过这个过程来评论代码,说明哪些有效,哪些无效 我为每一行得到了什么错误。提前谢谢。

        #
        # 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 ))

1 个答案:

答案 0 :(得分:7)

您需要round功能:

n2 = round(n, 2)

另外,要预先警告:花车是不精确的,当你转到两个地方,然后打印它们,它们可能看起来像它们有更多。您需要在格式字符串中使用%.2f来显示两个位置。如果你需要绝对的精确度(比如金钱),Decimal对你来说可能更好。