Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix failing rounding on Weight (#15275)

Maciej Korycinski5d2721a36364
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 0912fc0ef2..f8715a54e2 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -840,11 +840,23 @@ class AttributeValueBulkTranslateError(BulkError):
class Weight(graphene.ObjectType):
unit = WeightUnitsEnum(description="Weight unit.", required=True)
- value = graphene.Float(description="Weight value.", required=True)
+ value = graphene.Float(
+ description="Weight value. Returns a value with maximal three decimal places",
+ required=True,
+ )
class Meta:
description = "Represents weight value in a specific weight unit."
+ @staticmethod
+ def resolve_value(root, _info):
+ # Mass is stored as grams in the DB. It means that even if we provide the
+ # weight with static precision (e.g. 0.77 lb), the value will be converted
+ # to grams. In this case, input like 0.77 lb will be converted to
+ # 349.26583999999997 g. In case of retrieving the weight value in lb, we need
+ # to round the value as we will receive the value like 0.7699999999999999.
+ return round(root.value, 3)
+
class Image(graphene.ObjectType):
url = graphene.String(required=True, description="The URL of the image.")
diff --git a/saleor/graphql/product/tests/queries/test_product_type_query.py b/saleor/graphql/product/tests/queries/test_product_type_query.py
index 124eecbf1e..7125b5f953 100644
--- a/saleor/graphql/product/tests/queries/test_product_type_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_type_query.py
@@ -508,7 +508,7 @@ def test_product_type_query_by_id_weight_returned_in_default_unit(
product_data = content["data"]["productType"]
assert product_data is not None
assert product_data["name"] == product_type.name
- assert product_data["weight"]["value"] == 352.73999999999995
+ assert product_data["weight"]["value"] == round(product_type.weight.oz, 3)
assert product_data["weight"]["unit"] == WeightUnits.OZ.upper()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 01ff68fb09..80844e521e 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5519,7 +5519,7 @@ type Weight {
"""Weight unit."""
unit: WeightUnitsEnum!
- """Weight value."""
+ """Weight value. Returns a value with maximal three decimal places"""
value: Float!
}