Python 处理小数位数/避免使用科学符号
我有两条弦Python 处理小数位数/避免使用科学符号,python,regex,pandas,Python,Regex,Pandas,我有两条弦 string1 = '1000000000.0' string2 = '1000000000.09' from decimal import Decimal Decimal(string1).normalize() 给予 及 给予 我真的想要像上面那样 那么,string1如何可以作为十进制(100000000)而不是十进制('1E+9')呢 和字符串2作为十进制('100000000.09'),我目前得到的 您可能希望使用字符串格式。这使您能够非常密切地控制数据的表示方式—有关
string1 = '1000000000.0'
string2 = '1000000000.09'
from decimal import Decimal
Decimal(string1).normalize()
给予
及
给予
我真的想要像上面那样
那么,string1如何可以作为十进制(100000000)而不是十进制('1E+9')呢
和字符串2作为十进制('100000000.09'),我目前得到的 您可能希望使用字符串格式。这使您能够非常密切地控制数据的表示方式—有关完整的(对于初学者来说有点复杂的)解释,请参阅 要回答您的具体要求:
from decimal import Decimal
string1 = '1000000000.0'
string2 = '1000000000.09'
fstr = '{:10.0f} {:12.2f}'
print(fstr.format(Decimal(string1), Decimal(string2)))
您应该发现输出是
1000000000 1000000000.09
为了使您的输出更容易被人理解,您可能希望将fstr
更改为{:10、.0f}{:12、.2f}'
-逗号表示整数部分将被分成三个逗号分隔的组,您应该看到输出
1,000,000,000 1,000,000,000.09
这个函数起作用
def DecimalHandler(string):
if re.match('^\d*[.]?\d*$',string):
Frst = string.split('.')[0]
try:
secnd = string.split('.')[1]
secnd = re.sub('[0]+$','',secnd)
if secnd != '' :
secnd = '.'+secnd
else:
secnd = secnd
except IndexError:
secnd = ''
OutPut_Str = Frst+secnd
else:
print("...")
OutPut_Str = string
return(OutPut_Str)
有没有办法代替.2f的硬编码格式,如果“1000000000.9”将给出“1000000000.90”,但我希望它只会是“1000000000.9”,我想不出一种方法,只使用字符串格式,但是
'1000000000.90'。rstrip('0')
计算为'1000000000.9'
。不幸的是,这意味着如果没有有效的小数位,您将看到'100000000.
,这可能不是您想要的。数字格式化并不像看上去那么容易…是否有功能可以将“1E+9”扩展到100000000,这可能会奏效,也许你可以编辑这个问题,以便更全面地描述你实际要做的事情——最简单的方法是列出一个带有相应所需表示形式的数值列表。我希望输出像,10.90-->10.9,10.0-->10,1000000000.0-->1000000000, 10000000000.09 -----> 10000000000.09, 10000000000.90 ----->10000000000.9
1000000000 1000000000.09
1,000,000,000 1,000,000,000.09
def DecimalHandler(string):
if re.match('^\d*[.]?\d*$',string):
Frst = string.split('.')[0]
try:
secnd = string.split('.')[1]
secnd = re.sub('[0]+$','',secnd)
if secnd != '' :
secnd = '.'+secnd
else:
secnd = secnd
except IndexError:
secnd = ''
OutPut_Str = Frst+secnd
else:
print("...")
OutPut_Str = string
return(OutPut_Str)