0

I’ve got this code:

let rarity_from_db: Decimal = row.get("rarity");
let rarity = rarity_from_db.to_f64().unwrap_or_else(|| {
    error!(
        "Could not convert Numeric rarity value to f64 for record with ID {id}"
    );
    0.0
});

It’s inside a From trait implementation that converts data from a database Row type of tokio_postgres to my custom struct type, and in this specific case from Decimal to f64. The issue I get is that there are rows which have crazy numbers like 0.000000000000000000000002337556151251862 and the conversion fails with process panic:

thread 'tokio-runtime-worker' panicked at 'attempt to multiply with overflow'

I’m not sure:

  1. why the unwrap_or_else isn’t catching error (the process still panics)?
  2. how can I safely convert the decimal number?
Milkncookiez
  • 6,817
  • 10
  • 57
  • 96
  • 2
    I can't reproduce going from `"0.000000000000000000000002337556151251862"` to `Decimal` to `.to_f64()`. Is the panic coming from that or the `.get()` call from the `Row`? You could try `.try_get()` instead to handle deserialization errors. – kmdreko May 28 '23 at 18:35
  • No, I'm sure it's coming from the `.to_f64()` - I got it on the stack trace, the exact LoC. But I'll nevertheless try with `try_get()` – Milkncookiez May 28 '23 at 19:46
  • Sounds like a bug then – kmdreko May 28 '23 at 20:55
  • So, it seems like the biggest precision after the decimal point a variable of type Decimal can hold is 28, and I've got values that have 35+ digits. So, I can't even write a test to make a Decimal value from string of such a small number. I will just truncate the last few significant digits. – Milkncookiez May 29 '23 at 14:54

0 Answers0