Python (data precision processing)

A rounding processing

1.int () built-in function rounding down 

1 n = 3.75
2 print(int(n))
>>> 3 3 n = 3.25 4 print(int(n))
>>> 3

2.round () built-in function rounding

1 n = 3.75
2 print(round(n))
>>> 4 3 n = 3.25 4 print(round(n))
>>> 3

3. floor () function of rounding down the math module 

floor of the English Interpretation: the floor. As the name suggests is rounded down

Copy the code
1 import math
2 n = 3.75
3 print(math.floor(n))
>>> 3 4 n = 3.25 5 print(math.floor(n))
>>> 3
Copy the code

4.ceil () function of rounding up the math module

ceil English definition: the ceiling.

Copy the code
1 import math
2 n = 3.75
3 print(math.ceil(n))
>>> 4 4 n = 3.25 5 print(math.ceil(n))
>>> 4
Copy the code

5.modf () respectively take the integer part and a fractional part math function module

The method returns a decimal part and integer part tuple
Copy the code
1 import math
2 n = 3.75
3 print(math.modf(n))
>>> (0.75, 3.0) 4 n = 3.25 5 print(math.modf(n))
>>> (0.25, 3.0) 6 n = 4.2 7 print(math.modf(n))
(0.20000000000000018, 4.0)
Copy the code

The last output, related to another problem, that is, floating-point representation in the computer, the computer can not be accurately expressed decimal, at least for now the computer can not do this. The output of the last embodiment only in the calculation of an approximate 0.2 FIG. Like Python and C, using the IEEE 754 specification for storing floating point number.

 

Second, the fractional treatment

1. Data processing accuracy, of decimal places

(1)% f rounding techniques ---> "% .2f"

  • This method is the most conventional methods, convenient and practical
a = 1.23456

print ('%.4f' % a)
print ('%.3f' % a)
print ('%.2f' % a)

----->1.2346
----->1.235
----->1.23

 

(2) no rounding

  • Method 1: Use of the slices in the sequence
#coding=utf-8

a = 12.345
print str(a).split('.')[0] + '.' + str(a).split('.')[1][:2]


----> '12.34'

 

 

  • Method 2: Use a regular re matching module
import re
a = 12.345
print re.findall(r"\d{1,}?\.\d{2}", str(a))

---->['12.34']

 

Guess you like

Origin www.cnblogs.com/Mr-ZY/p/11779791.html