Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Pythonic way to print *at most* some number of decimal places [duplicate]

I want to format a list of floating-point numbers with at most, say, 2 decimal places. But, I don't want trailing zeros, and I don't want trailing decimal points.

So, for example, 4.001 => 4, 4.797 => 4.8, 8.992 => 8.99, 13.577 => 13.58.

The simple solution is ('%.2f' % f).rstrip('.0')('%.2f' % f).rstrip('0').rstrip('.'). But, that looks rather ugly and seems fragile. Any nicer solutions, maybe with some magical format flags?

like image 457
nneonneo Avatar asked Feb 21 '13 08:02

nneonneo


People also ask

How do I print a certain decimal place in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do you print numbers to two decimal places?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.

How do you do 2 decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

How do you print float to two decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


3 Answers

The g formatter limits the output to n significant digits, dropping trailing zeroes:

>>> "{:.3g}".format(1.234)
'1.23'
>>> "{:.3g}".format(1.2)
'1.2'
>>> "{:.3g}".format(1)
'1'
like image 81
Tim Pietzcker Avatar answered Sep 30 '22 02:09

Tim Pietzcker


You need to separate the 0 and the . stripping; that way you won't ever strip away the natural 0.

Alternatively, use the format() function, but that really comes down to the same thing:

format(f, '.2f').rstrip('0').rstrip('.')

Some tests:

>>> def formatted(f): return format(f, '.2f').rstrip('0').rstrip('.')
... 
>>> formatted(0.0)
'0'
>>> formatted(4.797)
'4.8'
>>> formatted(4.001)
'4'
>>> formatted(13.577)
'13.58'
>>> formatted(0.000000000000000000001)
'0'
>>> formatted(10000000000)
'10000000000'
like image 29
Martijn Pieters Avatar answered Sep 30 '22 02:09

Martijn Pieters


In general working with String[s] can be slow. However, this is another solution:

>>> from decimal import Decimal
>>> precision = Decimal('.00')
>>> Decimal('4.001').quantize(precision).normalize()
Decimal('4')
>>> Decimal('4.797').quantize(precision).normalize()
Decimal('4.8')
>>> Decimal('8.992').quantize(precision).normalize()
Decimal('8.99')
>>> Decimal('13.577').quantize(precision).normalize()
Decimal('13.58')

You may find more info here: http://docs.python.org/2/library/decimal.html

like image 43
Markon Avatar answered Sep 28 '22 02:09

Markon