Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To format floating-point numbers using the standard JSON module, you can use the "json.dumps()" function with the "default" parameter set to a function that converts floats to strings with the desired format.

Here is an example:

import json

def float_format(f):
    return '{:.2f}'.format(f)

data = {'value': 3.14159}

json_string = json.dumps(data, default=float_format)

print(json_string)  # output: '{"value": "3.14"}'

In this example, the "float_format" function converts floats to a string with two decimal places. The "json.dumps()" function uses this function to serialize the "data" dictionary to a JSON string. The resulting JSON string has the float value formatted as "3.14".