[Python] String ④ (Python floating-point precision control | control the width and precision of numbers)





1. Python string formatting




1. Floating point accuracy problem


In the previous blog [Python] string ③ (Python string formatting | single placeholder | multiple placeholders | different types of placeholders) , in the concatenated string, the float floating point type appears as follows , with 6 digits after the decimal point;

Code example:

# 不通过类型的占位符
name = "Tom"
age = 18
money = 88.88
info = "%s is %d years old, has %f dollors" % (name, age, money)
print(info)

Results of the :

Tom is 18 years old, has 88.880000 dollors

2. Floating point accuracy control


Use the auxiliary symbol "mn" to control the width and precision of the data;

  • m is used to control the width, if the set width is smaller than the width of the number itself, the setting will not take effect;
  • n is used to control the precision of the decimal point, the last digit will be rounded;

Example of floating-point precision control:

  • Set width: %3d used to set the width to 3 digits, if the number is 1, it is set to a width of 3 digits, when printing, two spaces will be added before 1;
    • 1When printing [空格][空格]1, 2 spaces are added in front to form 3 digits;
  • Set width and precision: %7.2f used to set the overall width to 7 (including the decimal point), and the decimal part to 2 digits;
    • 1When printing [空格][空格][空格]1.00, 3 spaces are added in front to form 7 digits;
  • Setting precision: %.3f used to set the precision of 3 digits after the decimal point, the width of the number is not limited to several digits;
    • 1when printed as 1.000;

Code example:

# 数字精度控制
num = 1
# 设置宽度
print("数字 1 宽度 5 : %5d" % num)

num = 1.01
# 设置 宽度 + 精度
print("数字 1.01 宽度 5 : %5.2f" % num)
# 设置精度
print("数字 1.01 精度 1: %.1f" % num)

Results of the :

数字 1 宽度 5 :     1
数字 1.01 宽度 5 :  1.01
数字 1.01 精度 1: 1.0

insert image description here

Guess you like

Origin blog.csdn.net/han1202012/article/details/130007635