Allow use of scientific notation on rust decimal (#4079)

* Allow use of scientific notation on rust decimal

* Add newsfragment

* Pull out var

* Fix clippy warning

* Modify let bindings location
This commit is contained in:
David Matos 2024-04-14 22:07:17 +02:00 committed by GitHub
parent cc7e16f4d6
commit 8ed5c17b93
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 2 deletions

View File

@ -0,0 +1 @@
Added support for scientific notation in `Decimal` conversion

View File

@ -64,8 +64,11 @@ 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()))
let py_str = &obj.str()?;
let rs_str = &py_str.to_cow()?;
Decimal::from_str(rs_str).or_else(|_| {
Decimal::from_scientific(rs_str).map_err(|e| PyValueError::new_err(e.to_string()))
})
}
}
}
@ -194,6 +197,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| {