0

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?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68

1 Answers1

1

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

Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68