Python numeric types: conversion of decimals and percentages

#Percentage conversion to decimals

s = '20%' # The percentage to be converted by default is a string
aa = float(s.strip('%')) # remove the% in the s string
bb = aa/100.0 #The operating environment is Python2.7, where there is a difference in division between Python2.X and python 3X
print bb
# The output result is 0.2

# Percentage of decimal conversion digits

#method one
a = 0.3214323
bb = "%.2f%%" % (a * 100)
print bb
# The output result is 32.14%

#Method Two
a = 0.3214323
b = str(a*100) + '%'
print b
# The output result is 32.14323%


# If you want to keep two decimal places
c = str(a)[:4]+ '%'
print c
# The output result is 0.32%

Guess you like

Origin blog.csdn.net/sanmi8276/article/details/108021180