Skip to content

Commit f11fcbd

Browse files
authored
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).
1 parent ab26a04 commit f11fcbd

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/graphql/utilities/ast_from_value.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,12 @@ def ast_from_value(value: Any, type_: GraphQLInputType) -> Optional[ValueNode]:
115115

116116
# Python ints and floats correspond nicely to Int and Float values.
117117
if isinstance(serialized, int):
118-
return IntValueNode(value=f"{serialized:d}")
118+
return IntValueNode(value=str(serialized))
119119
if isinstance(serialized, float) and isfinite(serialized):
120-
return FloatValueNode(value=f"{serialized:g}")
120+
value = str(serialized)
121+
if value.endswith('.0'):
122+
value = value[:-2]
123+
return FloatValueNode(value=value)
121124

122125
if isinstance(serialized, str):
123126
# Enum types use Enum literals.

tests/utilities/test_ast_from_value.py

+6
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ def converts_float_values_to_float_asts():
8686

8787
assert ast_from_value(1e40, GraphQLFloat) == FloatValueNode(value="1e+40")
8888

89+
assert ast_from_value(123456789.01234567, GraphQLFloat) == FloatValueNode(
90+
value="123456789.01234567"
91+
)
92+
93+
assert ast_from_value(1.1, GraphQLFloat) == FloatValueNode(value="1.1")
94+
8995
def converts_string_values_to_string_asts():
9096
assert ast_from_value("hello", GraphQLString) == StringValueNode(value="hello")
9197

0 commit comments

Comments
 (0)