python 格式化浮点数
我的输入是3.23,但是当我在上面使用float时,它变成3.2,
当我的输入是3.00时,当我在它上面浮动时,
当我从字符串转换为float时它变成3.0,我仍然希望它是3.00而不是3.0 是否可以? 我想知道实现这一点的代码,当我解决小数点到 2 位数字很重要的问题时,3.23 比 3.2 更好,精度更高
my input is 3.23, but when I use float on it, it becomes 3.2,
when my input is 3.00, when I do float on it, it becomes 3.0
when I convert to float from string, I still want it to be 3.00 and not 3.0
is it possible?
I want to know the code to make it possible, and when I am doing a problem in which the decimal point till 2 digits matter, 3.23 is better than 3.2, for more precision
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于该线程首先是“stringformatingdecimalpython”一词,我认为最好提供一个更新的答案:
Since this thread is first on the words "string formating decimal python", I think it's good to provide a more recent answer :
我想您想要的是将浮点数转换为具有所需小数位数的字符串。 您可以使用 %.3f 来实现这一点(这里 3 是您要打印的小数位数。例如:
值:3.00
I suppose that what you want is to convert a float to a string with the number of decimals that you want. You can achieve that using %.3f (here 3 is the number of decimals that you want to print. For example:
Value: 3.00
如果您想要十进制精度,请使用 python
decimal
模块:打印:
if you want decimal precision use the python
decimal
module:That prints:
如果您想将浮点数打印到所需的精度,您可以使用如下输出格式化代码:
假设 x = 3.125
这将在 python 2.6 中工作(我认为他们更改了版本 3 中的打印函数)。
您还应该意识到浮点数只能以一定的精度存储,因此有时您不会得到完全相同的数字。 例如,0.1 可以存储为 0.9999999987 之类的值。
If you want to print a floating-point number to a desired precision you can use output formatting codes like the following:
Assuming x = 3.125
This will work in python 2.6 (I think they changed the print function in version 3).
You should also realize that floating-point numbers can only be stored with a certain accuracy, so sometimes you will not get the exact same number back. For example 0.1 may be stored as something like 0.9999999987.