Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字符串中添加2个十进制数,保留精度_Python_Python 3.x_Math_Rounding - Fatal编程技术网

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

Python 在字符串中添加2个十进制数,保留精度,python,python-3.x,math,rounding,Python,Python 3.x,Math,Rounding,我有两个字符串,每个字符串包含一个十进制数,我们可以假设它们具有相同的精度 我不能只是硬编码精度,因为这些字符串集有时可能具有不同的精度 我只想将它们的两个值相加,使总和保持上述值的精度 其中一个值可能是负数,这就是为什么我想避免字符串拼接,这是我最初的想法 我的代码: str1 = "0.16107000" str2 = "0.00000270" total = abs(float(str1)) + abs(float(str2)) print("Total is " + str(total

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

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

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

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

我的代码:

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)
添加您的代码

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

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

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
Total is 70.00131251
如果你用另一个例子

str1 = "70.00000000"
str2 = "0.00131251"
这也提供了所需的输出:

Total is 0.16107270
Total is 70.00131251
作为你回答中的例子

str1 = "-70.00000000"
str2 = "0.00131251"
输出再次符合要求:

Total is -69.99868749
Total is 0.1000
最后,对于这个棘手的例子

str1 = "0.10"
str2 = "0.0000"
输出也符合要求:

Total is -69.99868749
Total is 0.1000

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

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
Total is 70.00131251
如果你用另一个例子

str1 = "70.00000000"
str2 = "0.00131251"
这也提供了所需的输出:

Total is 0.16107270
Total is 70.00131251
作为你回答中的例子

str1 = "-70.00000000"
str2 = "0.00131251"
输出再次符合要求:

Total is -69.99868749
Total is 0.1000
最后,对于这个棘手的例子

str1 = "0.10"
str2 = "0.0000"
输出也符合要求:

Total is -69.99868749
Total is 0.1000

这是使用ComplexidPhenomenon的原始代码,他建议根据小数点前的数字(不包括-sign)增加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

这是使用ComplexidPhenomenon的原始代码,他建议根据小数点前的数字(不包括-sign)增加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


这是一个被“精度”欺骗的问题。你是说小数点吗?(还有其他测量精度的方法,如有效数字)可能出现的最大小数位数和有效数字是多少?您使用的是哪一版本的Python?对,小数位。我正在使用Python 3.7。小数点后的最大位数为8。这是“精度”的重复问题。您是指小数点吗?(还有其他测量精度的方法,如有效数字)可能出现的最大小数位数和有效数字是多少?您使用的是哪一版本的Python?对,小数位。我正在使用Python 3.7。小数点后的最大位数是8。我认为这不是一个严肃的问题。但是,
.format()
将删除剩余的数字。他应该使用
str(四舍五入(总数,位数))
四舍五入到最后一位。但这似乎又是一个愚蠢的问题。我正在进行一个API调用,并将这些数字作为字符串接收。我必须添加它们,并进行另一个API调用,其中一个参数是总和,并且只接受我之前收到的相同精度。把我的问题说成“愚蠢”是很不礼貌的。我认为这不是一个严肃的问题。但是,
.format()
将删除剩余的数字。他应该使用
str(四舍五入(总数,位数))
四舍五入到最后一位。但这似乎又是一个愚蠢的问题。我正在进行一个API调用,并将这些数字作为字符串接收。我必须添加它们,并进行另一个API调用,其中一个参数是总和,并且只接受我之前收到的相同精度。将我的问题视为“愚蠢”是相当粗鲁的。提问者说,你不能“只是硬编码精度,因为这些字符串集有时可能具有不同的精度。”这一回答将精度硬编码为小数点后8位。类似于复杂的现象和Rory Daulton的解,当str1=“70.00000000”和str2=“0.00131251”,总数是70.001313,而不是我需要的70.00131251。@Dingo你可以设置
getcontext().prec=10
。提问者说你不能“只是硬编码精度,因为这些字符串有时可能有不同的精度。“这个答案将精度硬编码为小数点后8位。类似于复杂的现象和Rory Daulton的解决方案,当str1=“70.00000000”和str2=“0.00131251”时,总数是70.001313,而不是我需要的70.00131251。@Dingo您可以设置
getcontext().prec=10
。谢谢您的回复。但是,当:str1=“70.00000000”str2=“0.00131251”我需要总数为70.00131251,但最终为70时,这不起作用。001313@Dingo:谢谢你指出我答案中的一个错误。我现在已经改变了我的答案。我当前的代码在这种情况下工作,在许多其他情况下也是如此。感谢您的回复。但是,当:str1=“70.00000000”str2=“0.00131251”我需要总数为70.00131251,但最终为70时,这不起作用。001313@Dingo:谢谢你指出我答案中的一个错误。我现在已经改变了我的答案。我当前的代码在这种情况下有效,在许多其他情况下也有效。请注意,我更改了答案,不再使用
decimal
模块。我以前的代码并非在所有情况下都有效,而我相信我现在的代码有效。请注意,我更改了答案,不再使用
decimal
模块。我以前的代码并非在所有情况下都有效,而