在字符串中添加 2 个小数,保留精度

Adding 2 decimal numbers in strings, retaining precision

我有 2 个字符串,每个都包含一个十进制数,我们可以假设它们具有相同的精度。

我不能只对精度进行硬编码,因为这些字符串集有时可能具有不同的精度。

我只是想将它们的两个值相加,并使总和保持上述值的精度。

其中一个值可能有负数,这就是为什么我想避免字符串拼接的原因,这是我最初的想法。

我的代码:

str1 = "0.16107000" 
str2 = "0.00000270"
total = abs(float(str1)) + abs(float(str2))
print("Total is " + str(total))

输出:

Total is 0.16107269999999999

期望的输出:

Total is 0.16107270

另一个让事情变得棘手的例子:

str1 = "70.00000000" 
str2 = "0.00131251"

我需要总数为 70.00131251

最好的方法是什么?

>>> x = 3.1234567
>>> x = float('{:.3f}'.format(x))
>>> x
3.123

添加您的代码

x = float('{:.9f}'.format(total))
print(x)
from decimal import *
getcontext().prec = 8
str1 = "0.16107000" 
str2 = "0.00000270"
total = Decimal(str1)+Decimal(str2)
print("Total is " + str(total))
# Total is 0.16107270

这是一些代码。它看起来比需要的更复杂,但处理一般情况需要复杂性。如果这两个数字的小数位数不同,此代码将使用较大的数字,如果字符串表示精确值,这就是您想要的。

def get_decimal_places(dec_str: str) -> int:
    """Return the number of decimal places expressed in a number in a
    string. The string must have only an optional leading sign, decimal
    digits, and an optional single decimal point. No check is done on
    these requirements. If the string has no decimal point, the returned
    value is zero.
    """
    if "." in dec_str:
        return len(dec_str) - dec_str.find(".") - 1
    else:
        return 0


str1 = "0.16107000" 
str2 = "0.00000270"

dec_places = max(get_decimal_places(str1), get_decimal_places(str2))
print(f"Total is {float(str1) + float(str2):.{dec_places}f}")

此代码给出了所需的输出:

Total is 0.16107270

如果您使用其他示例,

str1 = "70.00000000"
str2 = "0.00131251"

这也给出了所需的输出:

Total is 70.00131251

以你的回答为例,

str1 = "-70.00000000"
str2 = "0.00131251"

输出再次符合预期:

Total is -69.99868749

最后,对于这个棘手的例子

str1 = "0.10"
str2 = "0.0000"

输出也是如愿:

Total is 0.1000

这是用ComplicatedPhenomenon的原代码,他建议根据小数点前的numbers(不包括-号)增加getcontext().prec,Rory Daulton的代码判断根据传递的字符串使用什么 getcontext().prec。

from decimal import Decimal, getcontext

def add_string_numbers(str1, str2):
    def get_decimal_places(dec_str: str) -> int:
        """Return the number of decimal places expressed in a number in a
        string. The string must have only an optional leading sign, decimal
        digits, and an optional single decimal point. If the string has no
        decimal point, the returned value is zero.
        """
        if "." in dec_str:
            return len(dec_str) - dec_str.find(".") + len([x for x in dec_str.split(".")[0] if x.isdigit()])
        else:
            return 0
    getcontext().prec = max(get_decimal_places(str1), get_decimal_places(str2))
    total = Decimal(str1) + Decimal(str2)    
    return total

str1 = "-70.00000000"
str2 = "0.00131251"

total = add_string_numbers(str1, str2)
print("Total is " + str(total))

结果:

Total is -69.99868749