Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BigDecimal into f64?

Tags:

rust

rust-sqlx

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?

like image 523
Roman Mahotskyi Avatar asked Oct 23 '25 17:10

Roman Mahotskyi


1 Answers

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

like image 158
Roman Mahotskyi Avatar answered Oct 26 '25 08:10

Roman Mahotskyi