Meloun
Meloun

Reputation: 15099

how to format float number as integer?

I am looking for a common formatting formula, where I dont loose precision but on the other hand I have no decimal points if not necessary

4.00 => "4"
1.23 => "1.23"

I've tried this

print "%.2f" % numvar

But for 4.00 I get 4.00

This format should be param passed as parameter to other function (see float_format http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html) so I don't need some if else solution.

Upvotes: 1

Views: 652

Answers (2)

Cyphase
Cyphase

Reputation: 12022

Use the %g formatting code.

>>> print '%g' % 3
3
>>> print '%g' % 3.1
3.1
>>> print '%g' % 3.14
3.14
>>> print '%g' % 3.14159
3.14159
>>> print '%g' % 3.1415926
3.14159
>>> print '%.6g' % 3.1415926
3.14159
>>> print '%.8g' % 3.1415926
3.1415926
>>> print '%.10g' % 3.1415926
3.1415926
>>> 

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180502

You could use a regex:

import re

def form(f, prec, spec):
    return re.sub("\.0+$", "", "{:.{prec}{spec}}".format(f, prec=prec, spec=spec))

Output:

In [2]: form(1.23, 2, "f")
Out[2]: '1.23'  
In [3]: form(4.00, 2, "f")
Out[3]: '4'    
In [4]: form(1.2302, 4, "f")
Out[4]: '1.2302'    
In [5]: form(1.0000, 4, "f")
Out[5]: '1'

Or if you were ok with 1.10 becoming 1.1 you could just rstrip:

print("{:.2f}".format(f).rstrip(".0"))

Upvotes: 0

Related Questions