In this tutorial, you will learn how to obtain only one decimal place in a number while using Python. Manipulating decimal places is a common task when working with numbers in programming. For instance, you may want to format currency, round the result to one decimal place, or perform a mathematical operation that requires specific precision.
Method 1: Format specifier method
First, we’ll look at using format specifiers to round a float to only one decimal place. Format specifiers are used in the %
operator.
Here’s how to do it:
1 2 3 |
decimal_number = 12.3456 formatted_number = "%.1f" % decimal_number print(formatted_number) # Output should be 12.3 |
The %
operator allows you to format the number using various format specifiers. In this case, we use %.1f
to specify that we want a float with one decimal place.
Method 2: round() function method
You can also use Python’s built-in round()
function to round a float to one decimal place. Here’s how to do it:
1 2 3 |
decimal_number = 12.3456 rounded_number = round(decimal_number, 1) print(rounded_number) # Output should be 12.3 |
The round()
function takes two arguments – the number to be rounded and the number of decimal places to round it to.
Method 3: Formatting string method
With Python 3, you can format strings using the format()
function. Here’s how to round a float to one decimal place using the format()
function:
1 2 3 |
decimal_number = 12.3456 formatted_number = "{:.1f}".format(decimal_number) print(formatted_number) # Output should be 12.3 |
The string {:.1f}
is a placeholder for the float to be filled by the format()
function. The .1f
inside the placeholder is a formatting specification that indicates a float with one decimal place.
1 2 3 4 5 6 7 8 |
decimal_number1 = 12.3456 formatted_number1 = "%.1f" % decimal_number1 rounded_number = round(decimal_number1, 1) formatted_number2 = "{:.1f}".format(decimal_number1) print("Format specifier method: ", formatted_number1) print("round() function method: ", rounded_number) print("Formatting string method: ", formatted_number2) |
Format specifier method: 12.3 round() function method: 12.3 Formatting string method: 12.3
Conclusion
In this tutorial, you have learned three different methods to format a number to have only one decimal place in Python. You can use the format specifier method, the round()
function, or the formatting string method according to your preference or specific use case. It’s good to be familiar with all the methods, as some might be more convenient in certain situations.