我有一个字典项目列表,我将遍历这些项目以更新到字典中。该字典将被转换为 json 字符串,该字符串将被插入到 SQL 数据库中。我的问题是字典项中的某些值可能非常小(或很大),因此 Python 会自动将其放入科学记数法中。
例如,我有这个字典:{"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}}。我已经能够使用我在下面创建的函数将科学计数法转换为精确值字符串。但现在我必须将它保留为一个字符串,因为一旦我在该字符串上使用 float(),它就会回到科学记数法。因此,当我使用 json.dumps() 将字典放入 json 字符串时,它会在那些字符串转换的浮点值周围创建不必要的引号:"{"Name": {"Key1 ": "0.000006", "Key2": "0.0000000001"}}"。我如何摆脱这些报价?
def format_float(self, value):
value_string = str(value)
# Anything smaller than or equal to 1e-5 will get converted to scientific notation
# If the value is in scientific notation
if 1e-323 <= abs(value) <= 1e-5:
# Split the string by the exponent sign
split_value_string = value_string.split("e-")
# Get the exponential
exponential = int(split_value_string[1])
# If there is a decimal, there could be digits after the decimal
if "." in split_value_string[0]:
precision = len(split_value_string[0].split(".")[1])
else:
precision = 0
f = "%.*f" % (exponential + precision, value)
elif value == float("inf") or value == float("-inf"):
return value
# Not in scientific notation
else:
if "." in value_string:
precision = len(value_string.split(".")[1])
else:
precision = 0
f = "%.*f" % (precision, value)
# No decimal
if "." not in f:
f += ".0"
p = f.partition(".")
s = "".join((p[0], p[1], p[2][0], p[2][1:].rstrip("0"))) # Get rid of the excess 0s
return s
请您参考如下方法:
float() 不应以科学记数法表示任何内容。只是当 python 打印一个非常长的 float 时,它以科学记数法打印它。尝试使用 json.dumps(),同时将值保持为 float,它应该可以满足您的需求。
编辑:让我重新措辞。 json.dumps() 将为您提供有效的 json。 json 规范允许将 float 作为科学记数法给出,因此它采用科学记数法这一事实应该不是问题。也就是说,如果您加载已转储的内容,它将为您提供一个 float,您可以按预期对其进行数学计算。例如:type(json.loads(json.dumps({'lol':1e-8}))['lol']) 给我 float
如果你真的需要让 json 中没有科学记数法,例如,如果读取 json 的东西不符合标准,那么你可以使用 json.dumps()将其转储为字符串,然后使用 re.sub() 替换数字。
precision = 10
re.sub('\d+e-?\d+',lambda x: '%.*f'%(precision,float(x.group())),json.dumps({'lol':1e-8}))
给我
'{"lol": 0.0000000100}'
