How to Round number in Python

How to Round number in Python

Python provides the built-in round() function, which used to round off a number to a given number of digits. It takes the two arguments, first is n, second is n digits and then it returns number n after rounding it to ndigits. By default, it rounds off the number n to the nearest integer.

For example – If we want to round off a number, let’s suppose 7.5. It will be rounded off to the nearest whole number is 7. However, the number 7.56 will be rounded off to 7.5 by one places to give.

The round() function is essential when working with the number of floats that may have many decimal places. The round() function makes easy and simple. The syntax is given below.

Syntax:

The parameters are –

  • number – It represents the given number to be rounded.
  • number of digits(Optional) – It represents the number of digits up to which the given number is to be rounded.

Let’s understand the following example –

Example –

Output:

15
26
25

Now, the second parameter is used.

Example –

Output:

25.47
25.428
25.42

The real-life example of the round() function

The round() function is most useful while changing fractions to decimals. We generally get the number of a decimal points such as if we do 1/3 then we get 0.333333334, but we use either two or three digits to the right of the decimal points. Let’s understand the following example.

Example –

Output:

0.16666666666666666
0.17

Another example

Example –

Output:

6
5
6

The round() function rounds 5.5 up to 6 and 6.5 down to 6. This is not a bug, the round() behaves like this way.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263600.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论