Currency in Rust


#1

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


#2

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

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


#3

The num crate has a BigRational type.


#4

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


#5

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


#6

As long as you don’t do any division.


#7

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.


#8

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.


#9

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);
}