Last active
August 25, 2023 09:20
-
-
Save Sukonnik-Illia/ed9b2bec1821cad437d1b8adb17406a3 to your computer and use it in GitHub Desktop.
Python 3 Json with 2 decimals after comma
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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