How to accurately output a JSON floating point number in python

Source: Internet
Author: User
This article describes how to accurately output a JSON floating point number in python. For more information about how to use floating point numbers in JSON, such as price and coordinates. But the floating point number in python is quite inaccurate, such as the following code:

The code is as follows:


#! /Usr/bin/env python

Import json as json

Data = [0.333, 0.999, 0.1]
Print json. dumps (data)


The output result is as follows:

The code is as follows:


$ Python floatjson. py
[0.33300000000000002, 0.999, 0.10000000000000001]


Can I specify the output format of a floating point number, for example, to the last two digits of the decimal point? There is a simple method, although compared with dirty:

The code is as follows:


#! /Usr/bin/env python

Import json
Json. encoder. FLOAT_REPR = lambda x: format (x, '. 3f ')

Data = [0.333, 0.999, 0.1]
Print json. dumps (data)


The output result is as follows:

The code is as follows:


$ Python floatjson. py
[0.333, 0.999, 0.100]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.