w3resource

Python: Print the following floating numbers upto 2 decimal places with a sign

Python String: Exercise-31 with Solution

Write a Python program to print the following numbers up to 2 decimal places with a sign.

Python String Exercises: Print the following floating numbers upto 2 decimal places with a sign

Sample Solution:

Python Code:

# Define a variable 'x' and assign it the value 3.1415926 (a positive floating-point number).
x = 3.1415926

# Define a variable 'y' and assign it the value -12.9999 (a negative floating-point number).
y = -12.9999

# Print an empty line for spacing.
print()

# Print the original value of 'x' with a label.
print("Original Number: ", x)

# Format the value of 'x' to two decimal places and include a sign (positive or negative) in the result.
print("Formatted Number with sign: "+"{:+.2f}".format(x))

# Print the original value of 'y' with a label.
print("Original Number: ", y)

# Format the value of 'y' to two decimal places and include a sign (positive or negative) in the result.
print("Formatted Number with sign: "+"{:+.2f}".format(y))

# Print an empty line for spacing.
print() 

Sample Output:

Original Number:  3.1415926                                                                                   
Formatted Number with sign: +3.14                                                                             
Original Number:  -12.9999                                                                                    
Formatted Number with sign: -13.00

Flowchart:

Flowchart: Print the following floating numbers upto 2 decimal places with sign

Python Code Editor:

Previous: Write a Python program to print the following floating numbers upto 2 decimal places.
Next: Write a Python program to print the following floating numbers with no decimal places.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.