在字符串中添加2个十进制数字,保持精度

时间:2019-08-09 09:16:59

标签: python python-3.x math rounding

我有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

最好的方法是什么?

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

添加您的代码

x = float('{:.9f}'.format(total))
print(x)

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

这使用了ComplicatedPhenomenon的原始代码,他的建议是根据小数点前的数字(不包括-号)增加getcontext()。prec,以及Rory Daulton的代码来确定什么getcontext()。可以根据传递的字符串进行使用。

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
相关问题