Python round() function with EXAMPLES

Round()

Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input.

If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

In this Python Tutorial, you will learn:

If the number after the decimal place given

  • >=5 than + 1 will be added to the final value
  • <5 than the final value will return as it is up to the decimal places mentioned.

Return value

It will return an integer value if the num_of_decimals is not given and a float value if the num_of_decimals is given. Please note the value will be rounded to +1 if the value after the decimal point is >=5 else it will return the value as it is up to the decimal places mentioned.

How much Impact can Rounding Have? (Rounding vs Truncation)

The best example to show the impact of rounding is for the stock exchange market. In the past i.e in the year 1982, the Vancouver Stock Exchange (VSE): used to truncate the stock values to three decimal places on each trade.

It was done almost 3000 times every day. The accumulated truncations lead to a loss of around 25 points per month.

An example of truncating the values versus rounding is shown below.

Consider the floating-point numbers generated below as stock values. Right now I am generating it for a range of

1,000,000 seconds between 0.01 and 0.05.

Example 1

In decimal, the quantize() method helps to round to a fixed number of decimal places, and you can specify the rounding to be used, as shown in the example below.

Example:

Using round() and decimal methods

top
X
Welcome to Our Website
Welcome to WPBot
wpChatIcon