From 50496f967f8209032b753912a4379eb9cea66627 Mon Sep 17 00:00:00 2001 From: Hannah Date: Mon, 18 Dec 2023 23:42:19 +0000 Subject: [PATCH] Adjust rounding logic when precision is `None` in `gr.Number()` (#6829) * adjust precision handling add test * add changeset * formatting --------- Co-authored-by: gradio-pr-bot --- .changeset/evil-bats-design.md | 5 +++++ gradio/components/number.py | 4 ++-- test/test_components.py | 22 +++++++++++++++++++++- 3 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 .changeset/evil-bats-design.md diff --git a/.changeset/evil-bats-design.md b/.changeset/evil-bats-design.md new file mode 100644 index 000000000000..5e8e9d5a4ab0 --- /dev/null +++ b/.changeset/evil-bats-design.md @@ -0,0 +1,5 @@ +--- +"gradio": patch +--- + +fix:Adjust rounding logic when precision is `None` in `gr.Number()` diff --git a/gradio/components/number.py b/gradio/components/number.py index aa8088653e10..3f44edb43d6a 100644 --- a/gradio/components/number.py +++ b/gradio/components/number.py @@ -99,10 +99,10 @@ def _round_to_precision(num: float | int, precision: int | None) -> float | int: num: Number to round. precision: Precision to round to. Returns: - rounded number + rounded number or the original number if precision is None """ if precision is None: - return float(num) + return num elif precision == 0: return int(round(num, precision)) else: diff --git a/test/test_components.py b/test/test_components.py index 5be21676daca..f96087f71e42 100644 --- a/test/test_components.py +++ b/test/test_components.py @@ -232,12 +232,32 @@ def test_component_functions_precision(self): assert numeric_input.postprocess(2.1421) == 2.14 assert numeric_input.postprocess(None) is None + def test_precision_none_with_integer(self): + """ + Preprocess, postprocess + """ + numeric_input = gr.Number(precision=None) + assert numeric_input.preprocess(5) == 5 + assert isinstance(numeric_input.preprocess(5), int) + assert numeric_input.postprocess(5) == 5 + assert isinstance(numeric_input.postprocess(5), int) + + def test_precision_none_with_float(self): + """ + Preprocess, postprocess + """ + numeric_input = gr.Number(value=5.5, precision=None) + assert numeric_input.preprocess(5.5) == 5.5 + assert isinstance(numeric_input.preprocess(5.5), float) + assert numeric_input.postprocess(5.5) == 5.5 + assert isinstance(numeric_input.postprocess(5.5), float) + def test_in_interface_as_input(self): """ Interface, process """ iface = gr.Interface(lambda x: x**2, "number", "textbox") - assert iface(2) == "4.0" + assert iface(2) == "4" def test_precision_0_in_interface(self): """