Python Format Number to 2 Decimal Places Example
Hi Dev,
This tutorial shows you python convert number to float with 2 decimal places. We will look at an example of python number to 2 decimal places. This article goes in detailed on python format number to 2 decimal places. We will look at an example of python round number to 2 decimal places.
You can convert a number to a float with 2 decimal places in Python by using the round() function. Here is an example:
Example 1:
In this example, we start with the number 4.14159265359. We then use the round() function to round the number to 2 decimal places, and assign the result to the float_number variable. Finally, we print the float_number variable, which will output 4.14.
main.py
number = 4.14159265359 # Convert number into float with 2 decimal floatNumber = round(number, 2) print(floatNumber)
Output:
4.14
Example 2:
In this example, we start with the string "4.14159265359". We first convert the string to a float using the float() function, and then round it to 2 decimal places using the round() function. Finally, we print the float_number variable, which will output 4.14.
main.py
numberStr = "4.14159265359" # Convert number into float with 2 decimal floatNumber = round(float(numberStr), 2) print(floatNumber)
Output:
4.14
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Add Image on Another Image in Python?
- Python Generate Random Number Between 1 and 10 Example
- How to Generate Random Number in Python?
- Python Smallest and Largest Numbers in a List Example
- How to Get Smallest Number in List Python?
- Python Generate List of Unique Random Numbers Example
- How to Create a List of Numbers from 1 to 100 in Python?
- How to Remove All Numbers from a String in Python?
- Python Count Number of Special Characters in String Example
- Python Count Number of Specific Words in String Example
- Python Count Number of Words in String Example
- How to Convert List to Lowercase in Python?
- Python Delete Directory if Exists Example