Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.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 如何将数字四舍五入为常量小数_Python - Fatal编程技术网

Python 如何将数字四舍五入为常量小数

Python 如何将数字四舍五入为常量小数,python,Python,我想使用“math.sqrt”,我的输出应该有4个小数点,即使是像“4”这样的数字。有什么办法吗?! 我使用了“round(num_sqrt,4)”但它不起作用 我的意见是: 1. 2. 3. 19 输出必须是: 1 1.4142 1.7320 4.3588 我的输出是: 1 1.4142 1.7320 4.3588试试这个 from decimal import Decimal import math # example with sqrt function y = Decimal(math

我想使用“math.sqrt”,我的输出应该有4个小数点,即使是像“4”这样的数字。有什么办法吗?! 我使用了“round(num_sqrt,4)”但它不起作用

我的意见是: 1. 2. 3. 19 输出必须是: 1 1.4142 1.7320 4.3588 我的输出是: 1 1.4142 1.7320 4.3588试试这个

from decimal import Decimal
import math

# example with sqrt function
y = Decimal(math.sqrt(4))
z = round(y, 4)
print(z) # output 2.0000

# First we take a float and convert it to a decimal
x = Decimal(16.0/7)
print(x)

# Then we round it to 4 places
output = round(x,4)
print(output) # outpun 2.2857

如果确实需要不必要的零,请尝试以下操作:

def format_floats(reference, values): formatted_values = [] for i in range(len(values)): length = len(str(reference)[str(reference).find("."):])-1 new_float = str(round(values[i], length)) new_float += "0"*(len(str(reference))-len(new_float)) formatted_values.append(new_float) return formatted_values if __name__ == '__main__': reference = 0.12345 values = [1.04, 2.045, 2.0] print(format_floats(reference, values)) def格式_浮动(参考、值): 格式化的_值=[] 对于范围内的i(len(值)): 长度=len(str(reference)[str(reference).find(“.”:)-1 新浮点数=str(四舍五入(值[i],长度)) 新浮点数+=“0”*(len(str(参考))-len(新浮点数)) 格式化的\u值。追加(新\u浮点) 返回格式化的值 如果uuu name uuuu==&apos__主要内容: 参考值=0.12345 数值=[1.04,2.045,2.0] 打印(格式_浮动(参考、值))
输出:['1.04000','2.04500','2.00000']

可能的重复听起来你的问题更多的是关于显示数字,而不是实际更改它的值。当你可以
打印('{.4f}.format(n)
时,似乎需要做大量的工作。我使用此代码输入参考值。