开发者

Getting a number of digits

I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals wit开发者_如何学Ch new Python format function ,but the function written there...

    >>> n = 4
    >>> p = math.pi
    >>> '{0:.{1}f}'.format(p, n)
    '3.1416'

...seems not to work in my case.

I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.

Thanks everyone, and sorry if this issue has already been posted.

Peixe


"%.3f" % math.pi

I know its using the old syntax but I personally prefer it.


What you have is fine (rounding the 5 up to a 6)

If you want truncation instead of rounding you could go:

from math import pi as p
print p
print int(p*10**4)/10.0**4

p=str(p).split(".")
p[1]=p[1][:4]
print ".".join(p)

output:

3.14159265359

3.1415

3.1415


If you only want the remainder of a float you could convert to a string and split on '.':

>>> str(math.pi).split('.')[1][:4]
<<< '1415'

or decimal.Decimal:

>>> Decimal(math.pi).as_tuple()[1][1:5]
<<< (1, 4, 1, 5)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜