python 格式化浮点数

发布于 2024-07-23 07:54:44 字数 186 浏览 3 评论 0原文

我的输入是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雨落星ぅ辰 2024-07-30 07:54:44

由于该线程首先是“stringformatingdecimalpython”一词,我认为最好提供一个更新的答案:

>>> P=34.3234564
>>> string="{:.2f}".format(P)
>>> string
'34.32'

Since this thread is first on the words "string formating decimal python", I think it's good to provide a more recent answer :

>>> P=34.3234564
>>> string="{:.2f}".format(P)
>>> string
'34.32'
叹倦 2024-07-30 07:54:44

我想您想要的是将浮点数转换为具有所需小数位数的字符串。 您可以使用 %.3f 来实现这一点(这里 3 是您要打印的小数位数。例如:

>>> print "Value: %.2f" % 3.0000

值: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:

>>> print "Value: %.2f" % 3.0000

Value: 3.00

反目相谮 2024-07-30 07:54:44

如果您想要十进制精度,请使用 python decimal 模块:

from decimal import Decimal
x = Decimal('3.00')
print x

打印:

Decimal('3.00')

if you want decimal precision use the python decimal module:

from decimal import Decimal
x = Decimal('3.00')
print x

That prints:

Decimal('3.00')
羁绊已千年 2024-07-30 07:54:44

如果您想将浮点数打印到所需的精度,您可以使用如下输出格式化代码:

假设 x = 3.125

print "%.1f" % (x)    # prints 3.1
print "%.2f" % (x)    # prints 3.12
print "%.3f" % (x)    # prints 3.125
print "%.4f" % (x)    # prints 3.1250

这将在 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

print "%.1f" % (x)    # prints 3.1
print "%.2f" % (x)    # prints 3.12
print "%.3f" % (x)    # prints 3.125
print "%.4f" % (x)    # prints 3.1250

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文