Ask Your Question
1

How to format floating-point numbers using the standard JSON module?

asked 2022-05-16 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-12-25 01:00:00 +0000

bukephalos gravatar image

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".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-16 11:00:00 +0000

Seen: 7 times

Last updated: Dec 25 '21