Skip to content

Commit

Permalink
Allow use of scientific notation on rust decimal (#4079)
Browse files Browse the repository at this point in the history
* Allow use of scientific notation on rust decimal

* Add newsfragment

* Pull out var

* Fix clippy warning

* Modify let bindings location
  • Loading branch information
dmatos2012 authored Apr 14, 2024
1 parent cc7e16f commit 8ed5c17
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
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
24 changes: 22 additions & 2 deletions src/conversions/rust_decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
})
}
}
}
Expand Down Expand Up @@ -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| {
Expand Down

0 comments on commit 8ed5c17

Please sign in to comment.