更改浮点精度并用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 ))

最佳答案

您需要round函数:

n2 = round(n, 2)

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

关于python - 更改浮点精度并用Python存储,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7489042/

10-09 17:14