Python retains the specified number of decimal places

Posted by literom on Fri, 19 Nov 2021 07:31:02 +0100

Python retains the specified number of decimal places

**1. '%. 2f'% f method (recommended)
2. format function (recommended)
3. round() function
4. Next, round and truncate directly**

1 '%. 2f'% f method (recommended)

// An highlighted block
f = 1.23456
print('%.4f' % f)    >1.2346
print('%.3f' % f)    >1.235
print('%.2f' % f)    >1.23

2 format function (recommended)

// An highlighted block
print(format(1.23456, '.2f'))     >1.23
print(format(1.23456, '.3f'))     >1.235
print(format(1.23456, '.4f'))     >1.2346

This method is rounded

3. Round() function

This method is not recommended. There are a lot of pits

// An highlighted block
a = 1.23456
b = 2.355
c = 3.5
d = 2.5
print(round(a,3))     >1.235 It's rounded here
print(round(b,2))     >2.35  There's no rounding here
print(round(c))       >4  Here 3.5 It's four
print(round(d))       >2   Here 2.5 It turned into 2

4. Truncation without rounding

1) You can enlarge the specified multiple, then round, and then divide by the specified multiple;

// An highlighted block
//Retain three decimal places and truncate Python 3
print(int(1.23456 * 1000) / 1000)   >1.234

2) Use string interception to intercept the number of digits specified after the decimal point

// An highlighted block
num = '123456'   //String num
print(num[:3])   >123

If 1.23456 takes 2 decimal places (intercepts 2 decimal places), you only need to intercept the one to the right of the decimal point as a string
partition() function: cut the string according to characters

// An highlighted block
num = '1.23456'  //String num
num_str = num.partition('.')
print(num_str)    >('1','.','23456')   //Tuple of three elements

Splicing strings: use of format function

Method 1:

// An highlighted block
def get_two_float(f_str,n):
	a,b,c = f_str.partition('.')
	c = c[:n]
	return '.'.join([a,c])

num = '1.23456'     //(1) Hidden danger 1: the passed in function is a string
print(get_two_float(num,2))   >1.23

num2 = '1.2'    //(2) Hidden danger 2: the decimal place of the incoming string is less than the final decimal place
print(get_two_float(num2,2))   >1.2

Final version:

// An highlighted block
def get_two_float(f_str, n):
	f_str = str(f_str)  // f_str = '{}'.format(f_str) can also be converted to a string
	a,b,c = f_str.partition('.')
	c = (c+'0' * n)[:n]   //No matter whether the incoming string is set to decimal, n decimal places 0 will be added after the string
	return '.'.join([a,c])

num = 1.23456
print(get_two_float(num,2))   >1.23

num2 = 123.4
print(get_two_float(num2,2))   >123.40

Python string formatting (%, format)

Two methods of string formatting in Python

  • %
  • format

Format format output

Compared with the% method for basic formatted output, format() is more powerful. This function takes the string as a template, formats it through the passed in parameters, and uses braces {} as a special character instead of%

1. format, location matching (most commonly used)

  • No number, i.e. {}
  • With numerical number, the sequence can be changed, i.e. {1}, {2} (parameters are numbered from 0)
  • With keyword, {name}

The format() method is used for string type formatting, and the basic format is;
< template string >. Format (< comma separated parameters >)
After calling the format() method, a new string will be returned, and the parameters will be numbered from 0;
The format() method can easily connect different types of variables or contents

// An highlighted block
"{}: computer{}of CPU Occupancy rate is{}%. ".format("2016-12-31","python",10)
>> '2016-12-31: computer python of CPU The occupancy rate is 10%. '
// An highlighted block
'PI{1}yes{2}{0}'.format('...',3.1415926,'Irrational number',)
>> 'PI 3.1415926 Is an irrational number...'
// An highlighted block
'Today is{name}of{key}Birthday party'.format(22,11,name = 'handsome guy',key = 18)
>>'Today is the handsome man's 18th birthday party'
'Today is{name}of{key}Birthday party, then{}'.format('test',name = 'handsome guy',key = 18)
>>'Today is the handsome man's 18th birthday party, and then on test'
// Errors will be reported below
'Today is{name}of{key}Birthday party, then{}'.format(name = 'handsome guy',key = 18,'test')

"Today is{0}of{}Birthday party".format("handsome guy", 18)

Summary:

  • When you only write {}, it is read in the order of the incoming values by default
  • When you write the number {1}, you can read the value of the corresponding position quotient, starting from 0
  • When you specify the keyword {name}, if you do not specify name = xxx, an error will be reported
  • When you specify a keyword and only write {}, the value passed in with the keyword must be written later, similar to a function (formal parameter first and actual parameter last)
  • {} and {1} cannot coexist
  • When format is used, the formatted output in a string is only used in one way. Do not mix them. It is easy to cause problems and unnecessary

2. format to specify the data type output

print("integer{:d}".format(123))   >>Integer 123
print("Floating point number{:5.2f}".format(123.19))   >>Floating point number 123.19
print("character string{:s}".format('123'))   >>String 123
print("octal number system{:o}".format(12))  >>Octal 14
print("hexadecimal{:x}".format(13))   >>hexadecimal d

Summary:

  • If: s is specified, only string values can be passed. If other types of values are passed, they will not be converted automatically;
  • When no type is specified, any type can be passed successfully. If there is no special need, the type can not be specified;
  • If you want to combine numbers and keywords, you can use the following:
// An highlighted block
print('keyword {num :d}'.format(num=123))   >Keywords 123
print('Number {0:d},{1:s}'.format(123,'123))   >Number 123123

3. format, digit complement

// An highlighted block
print('The default left alignment is 10 in width. If it is insufficient, fill in spaces:{:10}'.format('123'),'end')
print('Left aligned, width 10, insufficient space:{:<10}'.format('123'),'end')
print('Right aligned, width 10, insufficient space:{}{:>10}'.format('start','123'))
print('Right aligned, width is 10, take two decimal places, and make up 0 if it is insufficient:{:0>10.2f}'.format(222.225))

// results of enforcement
 The default left alignment is 10 in width and 123 in space        end
 Left aligned, width 10, insufficient space: 123        end
 Right aligned, width 10, insufficient space: start       123
 Right aligned, with a width of 10, take two decimal places, and make up 0:0000222 if it is insufficient.22

Summary:

  • The defau lt left alignment can be used without adding<
  • When no data type is specified, the value of any type passed can be successfully formatted for output

4. format, expand use

// An highlighted block
print("Always show symbols:{:0>+8.2f},{:0>+8.2f}".format(3.14, -3.14))

print("Percentage:{:%} {:.2%}".format(3 / 7, 3 / 7))

print("Comma separated, usually used in money {:,}".format(12345678)

//results of enforcement
 Always show symbol: 000+3.14,000-3.14
 Percentage: 42.857143% 42.86%
Comma separated, usually used in money 12,345,678

Summary:

  • +The significance of is that when we output positive numbers, we can also see symbols;
  • The percentage is a true percentage, not just an increase of%;
  • Fixed interval of three digits, the incoming string will report an error

Topics: Python