varunsrin / rusty_money

Money library for Rust
MIT License
85 stars 32 forks source link

`Money::from_str` returns `Err(InvalidAmount)` for typical cryptocurrency value #100

Open alopatindev opened 11 months ago

alopatindev commented 11 months ago
use rusty_money::{crypto, Money};

fn main() {
    let text = "1.11111111111";
    dbg!(Money::from_decimal(text.parse().unwrap(), crypto::ETH));
    dbg!(Money::from_str(text, crypto::ETH));
}
[src/main.rs:5] Money::from_decimal(text.parse().unwrap(), crypto::ETH) = Money {
    amount: 1.11111111111,
    currency: Currency {
        code: "ETH",
        exponent: 18,
        locale: EnUs,
        minor_units: 1000000000000000000,
        name: "Ethereum",
        symbol: "ETH",
        symbol_first: false,
    },
}
[src/main.rs:6] Money::from_str(text, crypto::ETH) = Err(
    InvalidAmount,
)
alopatindev commented 11 months ago

Sadly that's probably the only working way to parse cryptocurrency amounts returned by etherscan API right now:

let balance = "40891626854930000000000".parse::<i128>().unwrap(); // doesn't fit into i64, so we can't even call Money::from_minor
let currency = crypto::ETH;
dbg!(Money::from_decimal(
    Decimal::from_i128_with_scale(balance, currency.exponent()),
    currency,
));