Python string formatting controls numeric longitude

Python string formatting demonstrates the method of string formatting and splicing through placeholder splicing
, but you should have noticed that our 8.70
becomes 8.700000
insert image description here
, so we need to do a longitude control on floating point numbers

We first write the following code

dom1 = 110;
dom2 = 1234.1234567;
print(dom1)
print(dom2)

The result of the operation is as follows
insert image description here
We have defined an integer and a floating point number and we will use them for operations

Then we write the following code

dom1 = 110;
name = "限制dom1的长度为2位%12d"%(dom1)
print(name)

The running result is as follows.
insert image description here
There are a lot of spaces in front because we have %12d here, which means that the width of the value replacing this position must have 12 digits. If it is
not enough, just insert a space
and then we write it like this

dom1 = 110;
name = "限制dom1的长度为2位%1d"%(dom1)
print(name)

The running results are as follows.
insert image description here
You can see that we set it to %1d, but it still has three digits. This is another feature of it that cannot be smaller than itself.

Then we write the code

dom2 = 1234.1234567;
name = "限制dom1的长度为2位%.2f"%(dom2)
print(name)

The result of the operation is as follows.
insert image description here
You can see that we have limited the length to two digits and the decimal point will be removed. It only displays two

Then we change it to this

dom2 = 1234.1234567;
name = "限制dom1的长度为20位%.20f"%(dom2)
print(name)

insert image description here
It is also recommended that you keep two decimal places. Too long is sometimes a problem.

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/131196869