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

Wil*_*ild 3 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 ))
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 7

你想要的round功能:

n2 = round(n, 2)
Run Code Online (Sandbox Code Playgroud)

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