Skip to content

Commit

Permalink
Adjust rounding logic when precision is None in gr.Number() (#6829)
Browse files Browse the repository at this point in the history
* adjust precision handling
add test

* add changeset

* formatting

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
  • Loading branch information
hannahblair and gradio-pr-bot committed Dec 18, 2023
1 parent 1b9d423 commit 50496f9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/evil-bats-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"gradio": patch
---

fix:Adjust rounding logic when precision is `None` in `gr.Number()`
4 changes: 2 additions & 2 deletions gradio/components/number.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
22 changes: 21 additions & 1 deletion test/test_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down

0 comments on commit 50496f9

Please sign in to comment.