How can you format the output of a floating-point number to show only two decimal places?

0150

You can format the output of a floating-point number to show only two decimal places using the print() function with the % operator in Python. Here's an example:

num = 458.541315
formatted_num = "%.2f" % num
print(formatted_num)

This will output:

458.54

Alternatively, you can use the format() function or f-strings (if you're using Python 3.6 or later):

Using format():

formatted_num = "{:.2f}".format(num)
print(formatted_num)

Using f-strings:

formatted_num = f"{num:.2f}"
print(formatted_num)

Both of these methods will also output:

458.54

0 Comments

no data
Be the first to share your comment!