What is BigDecimal and how does it work?
trunkA BigDecimal allows storing any real number to arbitrary precision, which avoids common floating point errors (like 0.1 + 0.2 ≠ 0.3).
Internally, it uses a BigInt object paired with a 64-bit integer (scale) that determines the position of the decimal point. While the precision is described as arbitrary, it is practically limited to $2^{63}$ decimal places.
Important Note: It is not recommended to convert a floating-point number to a BigDecimal directly, as the floating-point representation may be unexpected. Instead, use string parsing.
use bigdecimal::BigDecimal;
use std::str::FromStr;
let input = "0.8";
let dec = BigDecimal::from_str(&input).unwrap();
let float = f32::from_str(&input).unwrap();
println!("Input ({}) with 10 decimals: {} vs {})", input, dec, float);