neversaint
neversaint

Reputation: 63994

How to make json decimal round to three digits

I have the following list of list:

x = [["foo",3.923239],["bar",1.22333]]

What I want to do is to convert the numeric value into 3 digits under JSON string. Yielding

myjsonfinal = "[["foo", 3.923], ["bar", 1.223]]"

I tried this but failed:

import json
print json.dumps(x)

Ideally we'd like this to be fast because need to deal with ~1000 items. Then load to web.

Upvotes: 0

Views: 130

Answers (2)

Jatin Bansal
Jatin Bansal

Reputation: 873

@neversaint, Try this:

x = [["foo", 3.923239], ["bar", 1.22333]]

for i, j in enumerate(x):
    x[i][1] = round(j[1], 3)

print x

Output:

[['foo', 3.923], ['bar', 1.223]]

Cheers!!

Upvotes: 1

monkut
monkut

Reputation: 43832

Try round()

import json
x = [["foo",3.923239],["bar",1.22333]]
json.dumps([[s, round(i, 3)] for s, i in x])

Upvotes: 2

Related Questions