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 <gradio-pr-bot@users.noreply.github.com>
This commit is contained in:
Hannah 2023-12-18 23:42:19 +00:00 committed by GitHub
parent 1b9d4234d6
commit 50496f967f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 3 deletions

View File

@ -0,0 +1,5 @@
---
"gradio": patch
---
fix:Adjust rounding logic when precision is `None` in `gr.Number()`

View File

@ -99,10 +99,10 @@ class Number(FormComponent):
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:

View File

@ -232,12 +232,32 @@ class TestNumber:
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):
"""