Skip to content

Fix scientific floats #774

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/input/parse_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl<'de> Deserialize<'de> for JsonInput {

if let JsonInput::String(s) = &first_value {
// Normalize the string to either an int or float
let normalized = if s.contains('.') {
let normalized = if s.contains('.') || s.contains('e') {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe there's a better way to do this check, or maybe there's a way to better-infer from serde_json itself that the value should be a number..? @davidhewitt @samuelcolvin @adriangb

Copy link
Collaborator Author

@dmontagu dmontagu Jul 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay after some unnecessarily thorough investigation (assisted by @adriangb, thanks) I'm pretty confident this approach is sufficiently optimized

JsonInput::Float(
s.parse()
.map_err(|e| V::Error::custom(format!("expected a float: {e}")))?,
Expand Down
6 changes: 6 additions & 0 deletions tests/validators/test_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,3 +325,9 @@ def test_non_finite_constrained_float_values(input_value, allow_inf_nan, expecte
v.validate_python(input_value)
else:
assert v.validate_python(input_value) == expected


def test_validate_scientific_notation_from_json():
v = SchemaValidator({'type': 'float'})
assert v.validate_json('1.0e-12') == 1e-12
assert v.validate_json('1e-12') == 1e-12