简体   繁体   English

Python大十进制舍入问题

[英]Python Big decimal round up issue

I am trying to store 我正在尝试存储

x=9999999999999.9999999999 

in a string variable. 在字符串变量中。 But it is getting round off. 但是它正在四舍五入。

c=str(9999999999999.9999999999)
print c
'1e+13'

Here I am trying to read a JSON file and converting it to CSV... But while reading 9999999999999.9999999999 it is automatically converted into 1e+13. 在这里,我尝试读取JSON文件并将其转换为CSV ...但是在读取9999999999999.9999999999它会自动转换为1e+13.

with open(inputfilename) as json_file:  
    data = json.load(json_file)
    selected_month=str(data['selected_month'])
    selected_year=str(data['selected_year'])
    record_count=str(data['record_count'])      
    for p in data['monthly_rates']:
        source_iso_currency_cd=p['source_iso_currency_cd']
        target_iso_currency_cd=p['target_iso_currency_cd']
        source_currency_cd=p['source_currency_cd']
        target_currency_cd=p['target_currency_cd']
        indirect_rate=p['indirect_rate']
        if indirect_rate == None:
            o_indirect_rate=""
        else:
            o_indirect_rate=repr(indirect_rate)

        direct_rate=p['direct_rate']
        if direct_rate == None:
            o_direct_rate=""
        else:
            o_direct_rate=repr(direct_rate)
        average_rate=p['average_rate']
        if average_rate == None:
            o_average_rate=""
        else:
            o_average_rate=repr(average_rate)

        o_str1=record_count+','+selected_month+','+selected_year+','+source_iso_currency_cd+','+target_iso_currency_cd+','+source_currency_cd+','+target_currency_cd+','+o_indirect_rate+','+o_direct_rate+','+o_average_rate

json normally parses float numbers into Python's float numbers, which cannot represent the precision you desire. json通常将浮点数解析为Python的浮点数,这不能代表您想要的精度。

Use either the built-in decimal , or another library, eg mpmath package's arbitrary-precision floats. 使用内置的decimal或其他库,例如mpmath包的任意精度浮点数。 You will need to tell json to use a different function for parsing floating-point numbers. 您将需要告诉json使用不同的函数来解析浮点数。

from decimal import Decimal
json.load(json_file, parse_float=Decimal)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM