简体   繁体   中英

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM