From f11fcbd619d10293a827636a143361920d716700 Mon Sep 17 00:00:00 2001 From: bennyweise Date: Sat, 2 Apr 2022 20:56:01 +1100 Subject: [PATCH] Serialize with maximum precision when converting float to FloatValue (#164) We make use of the float representation algorithm provided by the Python str method, which guarantees maximum precision while keeping the representation as short as possible, additionally removing the superfluous `.0` suffix for integers (same as in GraphQL.js). --- src/graphql/utilities/ast_from_value.py | 7 +++++-- tests/utilities/test_ast_from_value.py | 6 ++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/graphql/utilities/ast_from_value.py b/src/graphql/utilities/ast_from_value.py index 1f072cd3..0b3413cb 100644 --- a/src/graphql/utilities/ast_from_value.py +++ b/src/graphql/utilities/ast_from_value.py @@ -115,9 +115,12 @@ def ast_from_value(value: Any, type_: GraphQLInputType) -> Optional[ValueNode]: # Python ints and floats correspond nicely to Int and Float values. if isinstance(serialized, int): - return IntValueNode(value=f"{serialized:d}") + return IntValueNode(value=str(serialized)) if isinstance(serialized, float) and isfinite(serialized): - return FloatValueNode(value=f"{serialized:g}") + value = str(serialized) + if value.endswith('.0'): + value = value[:-2] + return FloatValueNode(value=value) if isinstance(serialized, str): # Enum types use Enum literals. diff --git a/tests/utilities/test_ast_from_value.py b/tests/utilities/test_ast_from_value.py index 90788143..de037ca4 100644 --- a/tests/utilities/test_ast_from_value.py +++ b/tests/utilities/test_ast_from_value.py @@ -86,6 +86,12 @@ def converts_float_values_to_float_asts(): assert ast_from_value(1e40, GraphQLFloat) == FloatValueNode(value="1e+40") + assert ast_from_value(123456789.01234567, GraphQLFloat) == FloatValueNode( + value="123456789.01234567" + ) + + assert ast_from_value(1.1, GraphQLFloat) == FloatValueNode(value="1.1") + def converts_string_values_to_string_asts(): assert ast_from_value("hello", GraphQLString) == StringValueNode(value="hello")