'How to display two decimal points in python, when a number is perfectly divisible?

Currently I am trying to solve a problem, where I am supposed to print the answer upto two decimal points without rounding off. I have used the below code for this purpose

import math
a=1.175                            #value of a after some division
print(math.floor(a*100)/100)

The output we get is:

1.17                              #Notice value which has two decimal points & not rounded

But the real problem starts when I try to print a number which is evenly divisible, after the decimal point only one zero is displayed. I have used the same code as above, but now

a=25/5                                   #Now a is perfectly divisible
print(math.floor(a*100)/100)

The output displayed now is

5.0                                      #Notice only one decimal place is printed

what must be done rectify this bug?



Solution 1:[1]

You can find this recommendation in the official Python tutorial: 15. Floating Point Arithmetic: Issues and Limitations.

For more pleasant output, you may wish to use string formatting to produce a limited number of significant digits

print("%.2f" % 3.0)
3.00

or

format(3.0, ".2f")
'3.00'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1