Skip to content

Commit

Permalink
Serialize with maximum precision when converting float to FloatValue (#…
Browse files Browse the repository at this point in the history
…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).
  • Loading branch information
bennyweise committed Apr 2, 2022
1 parent ab26a04 commit f11fcbd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/graphql/utilities/ast_from_value.py
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions tests/utilities/test_ast_from_value.py
Expand Up @@ -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")

Expand Down

0 comments on commit f11fcbd

Please sign in to comment.