简体   繁体   English

python圆形numpy数组,尾随0到一定的小数位数

[英]python round numpy array with trailing 0 to a certain number of decimals

I have a np array freq_vector filled with floating numbers. 我有一个np数组freq_vector充满浮点数。 For example freq_vector[0][0] is 200.00000000000003 例如freq_vector[0][0]200.00000000000003

I want to limit it to 4 decimals, then convert it to string for other usage. 我想将其限制为4位小数,然后将其转换为字符串以用于其他用途。

When I do round(freq_vector[0][0], 4) , the result is 200.0 , rather than 200.0000 当我做round(freq_vector[0][0], 4) ,结果是200.0 ,而不是200.0000

How can I get 200.0000 ? 我怎么能得到200.0000

In Python, 200.0000 is the same as 200.0 . 在Python中, 200.0000200.0相同。 Both are floating point numbers with the same value. 两者都是具有相同值的浮点数。 Since you want to convert them to strings, you can use the format method, such as the following: 由于要将它们转换为字符串,因此可以使用format方法,例如:

"{:.4f}".format(freq_vector[0][0])

Using the round() function is not necessary in this case. 在这种情况下,不需要使用round()函数。

In Python 3, you can use the simpler "f-string" syntax: 在Python 3中,可以使用更简单的“ f-string”语法:

f"{freq_vector[0][0]:.4f}"

You can find more information about this feature at PEP 498 . 您可以在PEP 498上找到有关此功能的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM