Explanation of rounding in Python

round() function

(Note: I don’t know if the following is correct, I just express my opinion)


For simple rounding operations, use the built-in round(value, ndigits) function

It is strongly recommended not to go deeper, just get the result directly.
ndigiths can be positive, negative, 0, or empty
n: it is accurate to the nth decimal and has no effect on integers, 1 is accurate to Tenths (Note: Decimals are pushed back from the tenths place)
-n: is accurate to the integer digits, -1 is accurate to the tenths place , and then the hundreds digits are thousands of places... If there are decimal places, all are dropped, no matter how big, But it will retain a decimal place of
0. 0: accurate to the ones place, but will retain a decimal place
of 0. Empty: accurate to the ones place, no decimal place

Fortunately, this critical point 5 is very annoying, I feel
it myself. According to my previous understanding, if 1.49 is accurate to the ones place, you should get 2 right, right, rounding from right to left, but the python running result 1
below is the fractional part

>>> round(1.49)
1
>>> round(1.5)
2
>>> round(0.5)
0
>>> round(0.51)
1
>>> round(0.051,1)
0.1
>>> round(0.05,1)
0.1
>>> round(0.046,1)
0.0
>>> round(0.25,1)
0.2
>>> round(0.35,1)
0.3
>>> round(0.251,1)
0.3

Here is an integer

>>> round(1235,-1)
1240
>>> round(1245,-1)
1240
>>> round(1234.99,-1)
1230.0
>>> round(1245,-2)
1200

This is my understanding of rounding that I checked on the Internet :
1. Same type algorithm: rounding six to fifty. Here, "four" means less than five, "six" means greater than five, and "five" means that the mantissa after the rounding digit is every five, and the first digit is taken, odd and even are not. For example, 1.25 retains one decimal place, because 2 is an even number, so it is 1.2.
2. From a statistical point of view, "rounding six to half a pair" is more scientific than "rounding". It makes some rounded results larger, some smaller, and more even. Rather than rounding at every five, the result is biased towards large numbers.
Python unclear what criteria is used to round off
I go online to search a bit in Python understanding of rounding:
in Python3, the choice of the way round function using near recent and equally close to the even-numbered (ROUND_HALF_EVEN) strategy
is not very understanding , spicy chicken ah
not to think, and think I will understand before rounding mixed up, I spent a lot of time, or do not know, harm, let it go
or want to suggest that you use directly, do not understand Oh, if you are a big brother, just treat me like I didn’t say, hehe

format() function

If you only want to print according to the format when outputting, use the format() function.

>>> format(1.45,'0.1f')
'1.4'
>>> format(1.35,'0.1f')
'1.4'
That's it, everyone can go to demonstrate
Remember to like it

Guess you like

Origin blog.csdn.net/hmh4640219/article/details/112660139