Home > Backend Development > Python Tutorial > How Can I Serialize Decimal Objects in JSON Without Losing Precision in Python?

How Can I Serialize Decimal Objects in JSON Without Losing Precision in Python?

DDD
Release: 2024-11-24 18:18:11
Original
431 people have browsed it

How Can I Serialize Decimal Objects in JSON Without Losing Precision in Python?

Serialization of Decimal Objects in Python's JSON

Encapsulating numbers as Decimal objects poses a challenge during JSON serialization. To achieve {'x': 3.9}, a float conversion is insufficient, resulting in an inaccurate '3.8999999999999999'.

Using SimpleJSON

SimpleJSON 2.1 and above offer a solution with native support for Decimal types. By default, use_decimal is enabled, resulting in the desired serialization:

import simplejson as json

json.dumps(Decimal('3.9'))  # Output: '3.9'
Copy after login

Stay Tuned

Anticipate the potential inclusion of this feature in Python's standard library to enhance JSON serialization capabilities for Decimal objects.

The above is the detailed content of How Can I Serialize Decimal Objects in JSON Without Losing Precision in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template