Featured image of post Rust: Working with precission

Rust: Working with precission

working with precission in Rust

Problem

when running this rust snippet code

1
2
3
4
5
6

fn main() {
    let num1 = 0.1;
    let num2 = 0.2;
    println!("sum = {}", num1 + num2);
}

we expect to have result 0.3. But the acual we got like

1
sum = 0.30000000000000004

Solution

Use package Decimal

to solve this, import Decimal pkg (https://docs.rs/rust_decimal/latest/rust_decimal). On the Cargo.toml, put

1
2
[dependencies]
rust_decimal = "1.28"

and change the main func to

1
2
3
4
5
6
7
8
use rust_decimal::Decimal;
use std::str::FromStr;

fn main() {
    let num1 = Decimal::from_str("0.1").unwrap();
    let num2 = Decimal::from_str("0.2").unwrap();
    println!("sum = {}", num1 + num2);
}

or

1
2
3
4
5
6
7
use rust_decimal::{prelude::FromPrimitive, Decimal};

fn main() {
    let num1 = Decimal::from_f64(0.1).unwrap();
    let num2 = Decimal::from_f64(0.2).unwrap();
    println!("sum = {}", num1 + num2);
}

run again the code, and then we can see the correct result 0.3

Use Macros

we also can use macros (https://docs.rs/rust_decimal_macros/latest/rust_decimal_macros/) for nice syntax.

run cargo add rust_decimal_macros or add it to the cargo.toml like previous, then change the main function to this:

1
2
3
4
5
6
7
use rust_decimal_macros::dec;

fn main() {
    let num1 = dec!(0.1);
    let num2 = dec!(0.2);
    println!("sum = {}", num1 + num2);
}

Note

  • unwarp() is a quick way to extract the value, but it will panic if the value is not present.
  • use unwrap_or_default() for safer way
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus