如何在 Python 中以精确的精度打印双精度值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34969226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:47:39  来源:igfitidea点击:

How do I print double in Python with exact precision?

pythondoubleprecision

提问by ALEXANDER KONSTANTINOV

I need to print double with precision equal exactly to 6, I found function round:

我需要以精确等于 6 的精度打印 double,我发现函数round

print(str(round(result, 6))

But in case resultitself has less precision, the print function skips zeros at the end.

但是如果结果本身的精度较低,打印函数会在最后跳过零。

Gor example, the output of such code,

Gor 例子,这样的代码的输出,

print(str(round(4.0, 6)))

is

4.0

But what I need is

但我需要的是

4.000000

How can I reach this?

我怎样才能达到这个目标?

回答by Matthew

Try using a format string:

尝试使用格式字符串:

print("%.6f"%4.0) # 4.000000

Or alternatively:

或者:

print("{:.6f}".format(4.0))

See the Python documentationfor details on format strings and more examples.

有关格式字符串和更多示例的详细信息,请参阅Python 文档