当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Write floating point numbers without any decimal places

问题描述:

I'm trying to have Python replicate some FORTRAN output of real values. My FORTRAN prints the real value as "31380.". I'm trying to replicate the same in Python--note that although I have no decimal places, I actually want the decimal point (period) to be printed. My current code is

htgm=31380.

print '{:6.0f}'.format(htgm)

which yields "31380". What am I doing wrong?

网友答案:

Python format language includes an 'alternate' form for floats which forces the decimal point by using a '#' in the format string:

>>> htgm=31380.
>>> format(htgm, '#.0f')
'31380.'

Which is what I think you are looking for.
I thought #g would be what you wanted but for some reason python adds the 0 back on:

>>> htgm=31380.
>>> format(htgm, 'g')
'31380'
>>> format(htgm, '#g')
'31380.0'
网友答案:

It is not possible to do it Python keeping the type of htgm as float. However if you are OK with making it as str, you may do:

htgm=31380.
'{0:.0f}.'.format(htgm)
# returns: '31380.'

# OR, even simply
'{}.'.format(int(htgm))
网友答案:

When you need to display the number, use:

print(str(htgm)[:-1])

This notation will shave off the last '0'.

分享给朋友:
您可能感兴趣的文章:
随机阅读: