简体   繁体   English

Python 2.7+:以非常精确的方式用非科学记法格式化浮点数的正确方法是什么?

[英]Python 2.7+: What's the correct way to format a float in non-scientific notation with certain precision?

I hope I am making sense with this question. 我希望我对这个问题有所了解。

Sometimes if I print a small float it'll look like 6.1248979238e-05 or something similar. 有时如果我打印一个小浮子,它看起来像6.1248979238e-05或类似的东西。

I want to be able to say "No matter what, output 10 digits precision like so": 0.abcdefghij 我希望能够说“无论如何,输出10位精度就像这样”: 0.abcdefghij

>>> '%0.10f'% 6.1248979238e-05 
'0.0000612490'

This is "string interpolation" or printf-style formatting which is still widely supported and used. 这是“字符串插值”或printf样式格式 ,仍然广泛支持和使用。 Another option is the newer style string formatting : 另一种选择是较新的样式字符串格式

>>> '{:.10f}'.format(6.1248979238e-05)
'0.0000612490'

Or if you want to be python2.6 compatible: 或者如果你想与python2.6兼容:

>>> '{0:.10f}'.format(6.1248979238e-05)
'0.0000612490'

Take your pick. 随便挑选。 Which version you use depends on which versions of python you want to support. 您使用的是哪个版本取决于您要支持的python版本。 If you're targeting only python2.7, it doesn't matter. 如果你针对python2.7,那没关系。 If you want to support earlier versions use printf-style. 如果要支持早期版本,请使用printf-style。 I've personally switched to using the last form in most of my code. 我个人在大部分代码中都转而使用最后一个表单。 I don't care about python2.5 support, but python2.6 is still new enough that I'd like to support it where possible. 我不关心python2.5的支持,但是python2.6仍然是新的,我想在可能的情况下支持它。

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

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