Skip to content

to_f64 returns an option but it cannot fail #727

@rollo-b2c2

Description

@rollo-b2c2

Hey this is a bit of an ergonomic issue, to_f64 returns an option, but it's actually infallible.

I can see this is a bit of a legacy wart of the api:

https://github.com/paupino/rust-decimal/blob/ba5ba1f661bf67a8e12bba8c9fdc438d69371e69/src/decimal.rs#L2526C1-L2527C1

    fn to_f64(&self) -> Option<f64> {
        if self.scale() == 0 {
            let integer = self.to_i64();
            match integer {
                Some(i) => Some(i as f64),
                None => None,
            }
        } else {
            // TODO: Utilize mantissa algorithm.
            match self.to_string().parse::<f64>() {
                Ok(s) => Some(s),
                Err(_) => None,
            }
        }
    }

Way back in 2020 it was optional, but no longer.

This is one of those things that causes me to double take EVERY time I do an unwrap: I'll check if there are actually any error cases to reassure myself that my unwrap isn't going to cause a really stupid panic in serialisation code.

Now it handles all possible paths I believe it's worth having an alternative function like as_f64. I gave some thought about the function name and 'as' makes the most amount of sense to me. I thought about unchecked or trusted those imply unsafeness or fallibility.

#726

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions