From ebe8923e72b9ff4997aef22bc27b169aa66c34c9 Mon Sep 17 00:00:00 2001 From: Ruud van Asseldonk Date: Sat, 24 Aug 2024 12:54:05 +0200 Subject: [PATCH] Implement float conversion for Python --- pyrcl/src/lib.rs | 2 +- pyrcl/test.py | 2 ++ src/decimal.rs | 7 +++++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/pyrcl/src/lib.rs b/pyrcl/src/lib.rs index 0376f72a..05d3356b 100644 --- a/pyrcl/src/lib.rs +++ b/pyrcl/src/lib.rs @@ -34,7 +34,7 @@ fn build_python_value(py: Python, v: &Value) -> PyResult { 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 diff --git a/pyrcl/test.py b/pyrcl/test.py index 111dfc2e..43812b5b 100644 --- a/pyrcl/test.py +++ b/pyrcl/test.py @@ -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") == { diff --git a/src/decimal.rs b/src/decimal.rs index 9eac0368..74a34eb3 100644 --- a/src/decimal.rs +++ b/src/decimal.rs @@ -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 {