Rounding decimal places python

10 ways to round to 2 decimal places in Python

In this post, we are going to learn different 10 ways to round to 2 decimal places in Python by using the python built-in round() function, str. format(),f-string, and all possible ways to round Float to 2 decimal places in python

What is Python round() function

The Python’s round() function rounds off a given number based on the number of digits passed for round off and returns a floating-point number. If the number of digits for round-off is not specified, the default value will be 0 and it returns the nearest integer.

Syntax

Parameters

  • number: The number that we have to round off.
  • digits: The number of digits up to the number to be rounded off.
Читайте также:  Применение абзацев

1. How to Round to 2 decimal Places python 3

In this example, we are using Python’s inbuilt round() function to round off a float number to 2 decimal places and using the print() function to print the result.

Program Exmaple

float_num = 15.68790 rounded_num = round(float_num,2) print('Round to 2 decimal Places :',rounded_num)
rounded to 5 decimal place: 12.50516 rounded to 2 decimal place: 1645.74 rounded to 3 decimal place: -200.75 rounded to 4 decimal place: 8.5432

3. Python str.format() to round to 2 Decimal Places

To round off up to 2 decimal places we can use the inbuilt python string function str.format() with “” a string and pass a float number as a parameter to the format() method. The round-off can be changed to different places for 3 decimal places and so on.

Program Example

float_num = 5.5667 two_dec_places = "".format(float_num) print('float to two decimal palace:\n',two_dec_places)
float to two decimal palace: 5.57

4. Python f-string to Round off to 2 Decimal Places

In this example, we are using the f-string to round off a number to 2 decimal palaces.

Program Example to round off to 2 decimal places

float_num = 5.8967 rounded_num = f"" print('rounded upto 2 decimal place :\n',rounded_num)
rounded upto 2 decimal place : 5.90

5. Using decimal Module

To get the correct precision, we can use the decimal module decimal() method of Python. Let us understand with an example, how to achieve this

Program Example

import decimal original_num = 8.5656789 float_num = decimal.Decimal(original_num) print('precision to 2 decimal place:',round(float_num,2) )
precision to 2 decimal places: 8.57

6. Regex to Truncate float Number to 2 Decimal Places

In this example, we are using the regular expression to Truncate floating Numbers to 2 Decimal Places, by defining a custom method. Here we are passing the number which we want to truncate to 2 decimal places and print the result after truncation.

Читайте также:  Скрипт python для начинающих

Program Example

import re def truncate_num(float_num): return re.sub(r'^(\d+\.\d)\d*$',r'',str(float_num)) print('rounded number to 2 decimal place :\n',truncate_num(float_num))
rounded number to 2 decimal place : 5.89

7. Custom function to Truncate float to 2 decimal places

In this example, we are using a custom truncate function that takes two arguments as float numbers & the number of digits up to where we have to truncate the number. Here we are truncating float numbers to 2 decimal places.

Program Example

float_num = 5.8967 def truncatenum(num,digits=0): multiplier = 10 ** digits return int(num * multiplier) / multiplier print('rounded number to 2 decimal place :\n',truncatenum(float_num,2))
rounded number to 2 decimal place : 5.89

8. Round a float number keeping ending zero

In this example, we are rounding off a float number to 2 decimal palaces keeping the ending zero and print the result using the print() function.

Python Program to round a float number keeping ending zero

float_num = 5.8967 round_keep_zero = "%.2f" % float_num print('round_keep_zero:\n',round_keep_zero)

9. Add extra zero after decimal in Python

In this example, we are adding extra zero after decimal places by using the format() method.

Program to Add extra zero after decimal in Python

float_num = 5.0 output_num = format(2.0, '.6f') print('add extra zero after decimal place :\n',output_num)
add extra zero after decimal place : 2.000000

10.Math module for Python Handling precision

The python math module has some built-in functionality to handle the precision.

  • trunc():-This math module function is used to remove all the decimal parts from the float number and return an integer part of a number.
  • ceil(): The ceil() math module is used to return the smallest integer number greater than the given number.
  • floor(): The floor() is used to return the greatest integer number smaller than the given number.

Program Example

import math float_num = 5.8967 print('number after using trunc() function :',math.trunc(float_num)) print('number after using ceil() function : ',math.ceil(float_num)) print('number after using floor() function : ',math.floor(float_num))
number after using trunc() function : 5 number after using ceil() function : 6 number after using floor() function : 5

Источник

How to Round to 2 Decimal Places in Python

Dillion Megida

Dillion Megida

How to Round to 2 Decimal Places in Python

Python provides many math methods for mathematical operations such as square roots, exponents, and so on.

In this article, I will show you how to round up a number to a specified decimal place.

What is a Decimal Place?

Look at this number: 324.89.

Each number here has a position which is refered to as place value. The place value of:

After the decimal point, you have two numbers: 8, then 9. The decimal place of a number is the position of the number after a decimal point (on the right side of it).

This definition means that the decimal place of 8 (in the tenths position) is 1, and 9 (in the hundredths position) is 2.

How to Round Up to a Certain Decimal Place

What does it mean then to round up to a certain decimal place? It means that you round up a number at a decimal place based on the number after it.

If the number after the decimal place is 5 or more, the number at the decimal place is rounded up +1. Otherwise, the number at the decimal place stays the same and the number after the decimal place is rounded down to 0.

For example, let’s say we want to round up 24.89 to 1 decimal place. Or you can put it as rounding up 24.89 to the nearest tenth.

The number 8 is at the 1 decimal place, and the number after 8 is 9. Since 9 is more than 5, 24.89, rounded up to the nearest tenth will be 24.9.

As another example, let’s take 24.82 and round it to 1 decimal place (the nearest tenth). Since 2 is not larger than 5, 8 remains the same, and 2 gets rounded down – resulting in 24.8.

How to Round Up a Decimal Place in Python

Now that you understand how to round up a decimal place, let’s see how to do it in Python.

You can use the global round function to round up numbers to a decimal place. The syntax is:

round(number, decimal_point) 

The function accepts the number and decimal_point as arguments. decimal_point specifies the decimal place that you want to round the number up to. Let’s see an example:

num = 24.89 rounded = round(num, 1) print(rounded) # 24.9 

Here’s another example of a longer number:

num = 20.4454 rounded3 = round(num, 3) # to 3 decimal places rounded2 = round(num, 2) # to 2 decimal places print(rounded3) # 20.445 print(rounded2) # 20.45 

For rounded3 , the num is rounded up to 3 decimal places. At the 3rd decimal place is 5, and the number that comes after it is 4. Since 4 is not greater than 5, the number 5 stays the same and 4 is rounded down to 0.

For rounded2 , the num is rounded up to 2 decimal places. At the 2nd decimal place is 4, and the number after it is 5. Since this number is greater than or equal to 5, the number 4 is rounded up to 5.

Conclusion

Rounding up numbers can be useful for keeping floating numbers within fixed digits.

For example, this is useful with currencies that only accept two decimal places (like the dollar: $100.99). In cases where a calculation for a product results in $50.678, you may want to round it to 2 decimal places, like this: $50.68. This way, it can be easier to give someone the actual monetary value.

In this article, I’ve briefly explained what decimal places are, and how to round numbers to certain decimal places in Python.

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Оцените статью