Thursday, June 11, 2020

How to print a float only upto two decimal places in Python

USE str.format() TO PRINT A FLOAT WITH TWO DECIMAL PLACES

Call str.format(number) with "{:.2f}" as str and a float as number to return a string representation of the number with two decimal places. Call print(string) with the formatted float-string as string to print the float.
a_float = 3.14159
formatted_float = "{:.2f}".format(a_float)

print(formatted_float)

OUTPUT
3.14

source: https://kite.com/python/answers/how-to-print-a-float-with-two-decimal-places-in-python#:~:text=Use%20str.&text=2f%7D%22%20as%20str%20and%20a,string%20to%20print%20the%20float.

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows