Skip to content

Instantly share code, notes, and snippets.

@Sukonnik-Illia
Last active August 25, 2023 09:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sukonnik-Illia/ed9b2bec1821cad437d1b8adb17406a3 to your computer and use it in GitHub Desktop.
Save Sukonnik-Illia/ed9b2bec1821cad437d1b8adb17406a3 to your computer and use it in GitHub Desktop.
Python 3 Json with 2 decimals after comma
# We need to ensure that c encoder will not be launched
@patch('json.encoder.c_make_encoder', None)
def json_dumps_with_two_digit_float(some_object):
# saving original method
of = json.encoder._make_iterencode
def inner(*args, **kwargs):
args = list(args)
# fifth argument is float formater which will we replace
args[4] = lambda o: '{:.2f}'.format(o)
return of(*args, **kwargs)
with patch('json.encoder._make_iterencode', wraps=inner):
return json.dumps(some_object)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment