decimal in rust
To work with decimal numbers in Rust, you can use the Decimal
type provided by the rust_decimal
crate. First, you need to add the rust_decimal
dependency to your project's Cargo.toml
file:
[dependencies]
rust_decimal = "1.0"
Then, in your Rust code, you can import the Decimal
type and use it to perform decimal arithmetic. Here's an example that demonstrates basic operations with decimal numbers:
use rust_decimal::Decimal;
fn main() {
let x = Decimal::from_str("3.14").unwrap();
let y = Decimal::from_str("2.71").unwrap();
let sum = x + y;
let difference = x - y;
let product = x * y;
let quotient = x / y;
println!("Sum: {}", sum);
println!("Difference: {}", difference);
println!("Product: {}", product);
println!("Quotient: {}", quotient);
}
This code imports the Decimal
type and the from_str
function from the rust_decimal
crate. It then creates two decimal numbers x
and y
using the from_str
function. The code performs addition, subtraction, multiplication, and division operations on the decimal numbers and prints the results.
Remember to handle potential errors when parsing decimal numbers by using unwrap()
or using proper error handling techniques in your code.
That's how you can work with decimal numbers in Rust using the rust_decimal
crate.