Search code examples
rustrust-sqlx

How to convert BigDecimal into f64?


I have a SQL query that returns a column with the BigDecimal type but my domain model works with f64:

price: Price::new(record.price).unwrap(),
                  ^^^^^^^^^^^^
                  rustc: mismatched types 
                     expected `f64`, found struct `BigDecimal`

How can I convert BigDecimal type into f64?


Solution

  • I was able to fix this problem by following steps

    1. Add bigdecimal crate to the project (cargo add bigdecimal)
    2. Add use bigdecimal::ToPrimitive; to the top of the file where I want to convert types.
    3. use .to_f64() method on my BigDecimal instance
    use bigdecimal::ToPrimitive;
    
    ...
    price: Price::new(record.price.to_f64().unwrap()).unwrap()
    ...
    

    The to_f64() method appeared on the BigDecimal type