parse_float Keeps JSON Decimals Exact
Parse JSON numbers with parse_float=Decimal, compare the float and Decimal totals, and keep currency arithmetic exact.
Code
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
decimalas 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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.IEEE 754 ConverterConvert decimal floats to and from IEEE 754 single- and double-precision bit patterns in hex and binary.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.