Home  >  Article  >  Backend Development  >  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
DDDOriginal
2024-11-24 18:18:11339browse

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'

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:
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