Currency in Rust

Hello,

at the moment I'm playing around with Rust and doing some programming exercises.
Coming from c# I'm used to have the decimal data type to do currency calculations.
Is there something similar in Rust or do I have to take care for correct calculations by myself?
What data type do you recommend to use for currency calculations to prevent rounding issues?

Best regards
Geaz

1 Like

I am not aware of any decimal number implementation for Rust.

Port of Python's decimal module would be a great project!

The num crate has a BigRational type.

3 Likes

How optimized is the code? I remember BigDecimal being subpar.

1 Like

If it came down to it you could always count in cents and then format as dollars.

As long as you don't do any division.

BigRational seems to be good, but is there a way to display a rational number as a decimal number?

For example: Display the rational 1/2 as 0.5.

For displaying purposes you could turn the rational into a float and print that. Or multiply by 100 and turn it into an integer and print that as cents.

Seems to work. I am doing all calculations with BigRationals.
And in the moment I want do display the values, I convert them to floats.

Thanks for your help!

Eample:

extern crate num;

use num::traits::ToPrimitive;
use num::bigint::BigInt;
use num::rational::Ratio;

fn main(){
    let one: Ratio<BigInt> = Ratio::from_float(1.0).unwrap();
    let two: Ratio<BigInt> = Ratio::from_float(2.0).unwrap();    
    let result = one / two;

    let float_result = result.numer().to_f64().unwrap() / result.denom().to_f64().unwrap();
    println!("{:.2}", float_result);
}