Skip to content

Commit

Permalink
Implement float conversion for Python
Browse files Browse the repository at this point in the history
  • Loading branch information
ruuda committed Aug 24, 2024
1 parent 13ca286 commit ebe8923
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyrcl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ fn build_python_value(py: Python, v: &Value) -> PyResult<PyObject> {
Value::Null => PyNone::get(py).into(),
Value::Bool(b) => b.to_object(py),
Value::Int(i) => i.to_object(py),
Value::Decimal(_) => unimplemented!("TODO: Convert to Python float."),
Value::Decimal(d) => d.to_f64().to_object(py),
Value::String(s) => s.to_object(py),
Value::List(xs) => {
let values = xs
Expand Down
2 changes: 2 additions & 0 deletions pyrcl/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
assert rcl.loads('["foobar"]') == ["foobar"]
assert rcl.loads("{1, 2, 3}") == {1, 2, 3}
assert rcl.loads('{1: "one", "two": 2}') == {1: "one", "two": 2}
assert rcl.loads("1.0") == 1.0
assert rcl.loads("0.25e-10") == 0.25e-10

# Test that loading files works. This needs to be executed from this directory.
assert rcl.load_file("test.rcl") == {
Expand Down
7 changes: 7 additions & 0 deletions src/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,13 @@ impl Decimal {
};
Some(result)
}

/// Convert to a float. For many decimals this will be a lossy operation.
pub fn to_f64(&self) -> f64 {
let n = self.numer as f64;
let exp = 10.0_f64.powi(self.exponent as i32);
n * exp
}
}

impl PartialEq for Decimal {
Expand Down

0 comments on commit ebe8923

Please sign in to comment.