Macro dec

dec!() { /* proc-macro */ }
Expand description

Transform a literal number directly to a Decimal at compile time.

Any Rust number format works, for example:

  • dec!(1), dec!(-1), dec!(1_999), dec!(- 1_999)
  • dec!(0b1), dec!(-0b1_1111), dec!(0o1), dec!(-0o1_777), dec!(0x1), dec!(-0x1_Ffff)
  • dec!(1.), dec!(-1.111_009), dec!(1e6), dec!(-1.2e+6), dec!(12e-6), dec!(-1.2e-6)

§Option radix

You can give it integers (not float-like) in any radix from 2 to 36 inclusive, using the letters too: dec!(100, radix 2) == 4, dec!(-1_222, radix 3) == -53, dec!(z1, radix 36) == 1261, dec!(-1_xyz, radix 36) == -90683

§Option exp

This is the same as the e 10’s exponent in float syntax (except as a Rust expression it doesn’t accept a unary +.) You need this for other radixes. Currently, it must be between -28 and +28 inclusive: dec!(10, radix 2, exp 5) == 200_000, dec!( -1_777, exp -3, radix 8) == dec!(-1.023)

§Example

use rust_decimal_macros::dec;

// If the reexportable feature is enabled, `Decimal` needs to be in scope
#[cfg(feature = "reexportable")]
use rust_decimal::Decimal;

let number = dec!(1.2345);
assert_eq!("1.2345", number.to_string());
let number = dec!(-5.4321);
assert_eq!("-5.4321", number.to_string());
let number = dec!(-0o1_777);
assert_eq!("-1023", number.to_string());
let number = dec!(-1_777, radix 8);
assert_eq!("-1023", number.to_string());