parse_float Keeps JSON Decimals Exact

Parse JSON numbers with parse_float=Decimal, compare the float and Decimal totals, and keep currency arithmetic exact.

PythonData Integrity

Code

pythonsnippet
25 lines
import json
from decimal import Decimal


PAYLOAD = '{"price": 19.99, "quantity": 7, "tax_rate": 0.075}'


def main() -> None:
    default = json.loads(PAYLOAD)
    exact = json.loads(PAYLOAD, parse_float=Decimal)

    print('float price:', default['price'])
    print('float total repr:', repr(default['price'] * default['quantity']))
    print('decimal price:', exact['price'])
    print('decimal total:', exact['price'] * exact['quantity'])
    print('float tax:', default['price'] * default['tax_rate'])
    print('decimal tax:', exact['price'] * exact['tax_rate'])
    print('types:', type(default['price']).__name__, type(exact['price']).__name__)

    encoded = json.dumps({'total': str(exact['price'] * exact['quantity'])})
    print('encoded:', encoded)


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

float price: 19.99
float total repr: 139.92999999999998
decimal price: 19.99
decimal total: 139.93
float tax: 1.4992499999999997
decimal tax: 1.49925
types: float Decimal
encoded: {"total": "139.93"}

What the code does

parse_float Keeps JSON Decimals Exact is built around the function main.

Reach for decimal and what you get is Decimal — that is the whole API contact area.

What to watch for

  • Requires decimal as a package; the snippet will not run without it.

Applying it

Output lines are prefixed (float price:, float total repr:, decimal price:), making each step’s effect easy to spot.

Interactive Tools for This Topic

FAQ

What does parse_float Keeps JSON Decimals Exact print when run?
Run it as a complete program — the output lines carry labels such as `float price:`, `float total repr:`, `decimal price:`.