[英]Handling Decimal Places / Avoid Scientific Notation Python
I have 2 Strings namely 我有2个字符串
string1 = '1000000000.0'
string2 = '1000000000.09'
from decimal import Decimal
Decimal(string1).normalize()
gives 给
Decimal('1E+9')
and 和
Decimal(string2).normalize()
gives 给
Decimal('1000000000.09')
Which i actually want like the above. 我实际上想要像上面那样。
so how can string1 be as Decimal(1000000000) instead of Decimal('1E+9') and string2 as Decimal('1000000000.09') which i get in currently.!! 所以如何将string1作为Decimal(1000000000)而不是Decimal('1E + 9')和string2作为Decimal('1000000000.09'),我目前正在使用它!
You probably want to use string formatting. 您可能要使用字符串格式。 This gives you very close control over how your data is represented - see the documentation on
str.format
for a full (and a little complex for a beginner) explanation. 这使您可以非常紧密地控制数据的表示方式- 有关完整(对于初学者而言有点复杂)的说明,请参阅
str.format
上的文档 。
To answer your specific request: 要回答您的特定要求:
from decimal import Decimal
string1 = '1000000000.0'
string2 = '1000000000.09'
fstr = '{:10.0f} {:12.2f}'
print(fstr.format(Decimal(string1), Decimal(string2)))
You should find the output is 您应该找到的输出是
1000000000 1000000000.09
To make your output easier to understand by humans, you might want to change fstr
to '{:10,.0f} {:12,.2f}'
- the commas indicate that the integer part is to be split into comma-separated groups of three, and you should see the output 为了使您的输出更容易
fstr
理解,您可能需要将fstr
更改为'{:10,.0f} {:12,.2f}'
-逗号指示整数部分将被分成逗号分隔的组之三,您应该会看到输出
1,000,000,000 1,000,000,000.09
This Functions Do the Trick 此功能可以欺骗
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.