Skip to content
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

Allow use of scientific notation on rust decimal #4079

Merged
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions newsfragments/4079.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added support for scientific notation in `Decimal` conversion
23 changes: 21 additions & 2 deletions src/conversions/rust_decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ impl FromPyObject<'_> for Decimal {
if let Ok(val) = obj.extract() {
Ok(Decimal::new(val, 0))
} else {
Decimal::from_str(&obj.str()?.to_cow()?)
.map_err(|e| PyValueError::new_err(e.to_string()))
Decimal::from_str(&obj.str()?.to_cow()?).or_else(|_| {
adamreichold marked this conversation as resolved.
Show resolved Hide resolved
Decimal::from_scientific(&obj.str()?.to_cow()?)
.map_err(|e| PyValueError::new_err(e.to_string()))
})
}
}
}
Expand Down Expand Up @@ -194,6 +196,23 @@ mod test_rust_decimal {
})
}

#[test]
fn test_scientific_notation() {
Python::with_gil(|py| {
let locals = PyDict::new_bound(py);
py.run_bound(
"import decimal\npy_dec = decimal.Decimal(\"1e3\")",
None,
Some(&locals),
)
.unwrap();
let py_dec = locals.get_item("py_dec").unwrap().unwrap();
let roundtripped: Decimal = py_dec.extract().unwrap();
let rs_dec = Decimal::from_scientific("1e3").unwrap();
assert_eq!(rs_dec, roundtripped);
})
}

#[test]
fn test_infinity() {
Python::with_gil(|py| {
Expand Down
Loading