在 Python 中的小数点后向浮点数添加零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15619096/
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
Add zeros to a float after the decimal point in Python
提问by
I am reading in data from a file, modify it and write it to another file. The new file will be read by another program and therefore it is crucial to carry over the exact formatting
我正在从文件中读取数据,对其进行修改并将其写入另一个文件。新文件将由另一个程序读取,因此保留确切的格式至关重要
for example, one of the numbers on my input file is:
例如,我的输入文件中的数字之一是:
1.000000
my script applies some math to the columns and should return
我的脚本对列应用了一些数学运算,应该返回
2.000000
But what is currently returned is
但目前返回的是
2.0
How would I write a float for example my_float = 2.0, as my_float = 2.00000to a file?
例如my_float = 2.0,my_float = 2.00000对于文件,我将如何编写浮点数?
采纳答案by Martijn Pieters
Format it to 6 decimal places:
将其格式化为 6 位小数:
format(value, '.6f')
Demo:
演示:
>>> format(2.0, '.6f')
'2.000000'
The format()functionturns values to strings following the formatting instructionsgiven.
该format()函数按照给定的格式说明将值转换为字符串。
回答by chason
An answer using the format() command is above, but you may want to look into the Decimal standard library object if you're working with floats that need to represent an exact value. You can set the precision and rounding in its context class, but by default it will retain the number of zeros you place into it:
使用 format() 命令的答案在上面,但如果您正在使用需要表示精确值的浮点数,您可能需要查看 Decimal 标准库对象。您可以在其上下文类中设置精度和舍入,但默认情况下它将保留您放入其中的零数:
>>> import decimal
>>> x = decimal.Decimal('2.0000')
>>> x
Decimal('2.0000')
>>> print x
2.0000
>>> print "{0} is a great number.".format(x)
2.0000 is a great number.
回答by Iqra.
I've tried n ways but nothing worked that way I was wanting in, at last, this worked for me.
我已经尝试了 n 种方法,但没有任何方法能达到我想要的效果,最后,这对我有用。
foo = 56
print (format(foo, '.1f'))
print (format(foo, '.2f'))
print (format(foo, '.3f'))
print (format(foo, '.5f'))
output:
56.0
56.00
56.000
56.00000
Meaning that the 2nd argument of formattakes the decimal places you'd have to go up to. Keep in mind that formatreturns string.
这意味着第二个参数format需要你必须上升到的小数位。请记住,format返回字符串。

