Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing floats with a specific number of zeros

I know how to control the number of decimals, but how do I control the number of zeros specifically?

For example:

104.06250000 -> 104.0625   
119.00000 -> 119.0  
72.000000 -> 72.0 
like image 899
zequzd Avatar asked Jun 11 '09 13:06

zequzd


People also ask

How do I print float values without trailing zeros?

To format floats without trailing zeros with Python, we can use the rstrip method. We interpolate x into a string and then call rstrip with 0 and '. ' to remove trailing zeroes from the number strings. Therefore, n is 3.14.

How do I print float numbers?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

How do you print extra zeros after a decimal in Python?

Use the format() function to add zeros to a float after the decimal, e.g. result = format(my_float, '. 3f') . The function will format the number with exactly N digits following the decimal point.

How do you control the number of decimal places to be printed in float value?

You can do: printf("%. 2lf\n", F); printf("%. 3lf\n", F); printf("%.


1 Answers

How about using the decimal module?

From the documentation:

"The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For multiplication, the “schoolbook” approach uses all the figures in the multiplicands. For instance, 1.3 * 1.2 gives 1.56 while 1.30 * 1.20 gives 1.5600."

The normalize() function removes trailing zeros:

>>> from decimal import *
>>> d1 = Decimal("1.30")
>>> d2 = Decimal("1.20")
>>> d3
Decimal("1.5600")
>>> d3.normalize()
Decimal("1.56")
like image 69
mechanical_meat Avatar answered Nov 11 '22 20:11

mechanical_meat