1 %.2f' %[variable] [rounded]
It can be used at the place where print() is printed, or it can be assigned to a new variable for output
# 四舍五入方法
a = 2.345566
print('%.4f'% a)
# 2.3456
print('%.3f'% a)
# 2.346
print('%.2f'% a)
# 2.35
# 赋值给新的变量
c = '%.2f'% a
print(c)
# 2.35
2 format function [rounding]
It can be used at the place where print() is printed, or it can be assigned to a new variable for output
# 四舍五入方法
a = 2.345566
print(format(a, '.4f'))
# 2.3456
print(format(a, '.3f'))
# 2.346
# 赋值给新的变量
c = format(a, '.4f')
print(c)
# 2.3456
3 Direct truncation [without rounding]
3.1 First enlarge the specified multiple, then round up, and then divide by the specified multiple
1 Reserve three decimal places: first ×100, then int, then ÷100
a = 2.345566
c = int(a * 100) / 100
print(c)
# 2.34
2 Reserve three decimal places: first ×1000, then int, then ÷1000
a = 2.345566
c = int(a * 1000) / 1000
print(c)
# 2.345
3 Keep four decimal places: first ×10000, then int, then ÷10000
a = 2.345566
c = int(a * 10000) / 10000
print(c)
# 2.3455
3.2 Convert to a string for string interception, and intercept the specified number of digits after the decimal point [without rounding] [not recommended and a bit troublesome]
a = 2.345566
# 进行分割
a_0 = str(a).split('.')[0]
a_1 = str(a).split('.')[1]
# 截取小数点后的
a_point = a_1[0:2] # 截取2位
# 字符串连接
a_new = a_0 + '.' + a_point
# 将string类型转换为float类型
a_new_number = float(a_new)
print(a_new_number)
# 2.34
4 round() function [accurate rounding, but cannot guarantee the same number of decimal places]
round(number, ndigits=None)
returns the number rounded to ndigits precision after the decimal point. If ndigits is omitted or None, it returns the nearest integer to its input.
Note:
The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it's because most decimal fractions cannot be represented exactly as floating point values.
5 Numpy array np.set_printoptions [rounded]
It can only be used for printing, and cannot be assigned
np.set_printoptions(precision=3, suppress=True, formatter={})
precision: keep a few decimal places, and will not add 0 later
supress: do not use scientific notation for very large/small numbers (True)
formatter: force formatting, will add 0 later
import numpy as np
a = np.random.random(3)
print('before set precision: \n',a)
np.set_printoptions(precision=3, suppress=True)
print('after set precision: \n',a)
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print('after set formatter: \n',a)
# before set options:
# [ 0.05856348 0.5400039 0.70000603]
# after set precision:
# [ 0.059 0.54 0.7]
# after set formatter:【强制补0】
# [ 0.059 0.540 0.700]
6 Summary
The 1st, 2nd, and 4th methods can perform rounding, and can assign values to variables.
The third method cannot perform rounding, and can assign values to variables.
The fifth method can perform rounding, but cannot assign values.
Learning link: