xur_

> module

std::decimal

arbitrary-precision decimal numbers

use std::decimal; feature rust_decimal in the browser

std::decimal provides a Decimal type backed by the rust_decimal crate, giving 96 bits of significand with a scale of 0–28.

Decimals avoid the rounding issues of floating-point arithmetic and are the native representation of .NET System.Decimal values, making them essential for interacting with CoreCLR methods that take or return decimals.

> functions

# from_float(value: f64) -> Result<Decimal, Error>

A decimal close to the float's value (0.1 gives 0.1). Err(decimal::Error::OutOfRange) if the float can't be represented, such as NaN, infinity or a value too large.

# from_int(value: i64) -> Decimal

A decimal with the integer's value.

# from_str(value: str) -> Result<Decimal, Error>

Parses a string such as "3.14", "-100.5" or "1e3". Err(decimal::Error::Parse) if it isn't a valid decimal.

> types

┌ type Decimal

Wrapper so we can derive Facet and register as a native type.

# decimal.abs() -> Decimal

The absolute value.

# decimal.ceil() -> Decimal

Rounds towards negative or positive infinity.

# decimal.floor() -> Decimal

Rounds towards negative or positive infinity.

# decimal.is_sign_negative() -> bool

Whether the sign is negative or positive. Zero is positive.

# decimal.is_sign_positive() -> bool

Whether the sign is negative or positive. Zero is positive.

# decimal.round() -> Decimal

Rounds to a whole number, halves to even (2.5 gives 2, 3.5 gives 4).

# decimal.round_dp(dp: i64) -> Decimal

Rounds to dp decimal places, halves to even.

# decimal.scale() -> i64

The number of decimal places (0–28).

# decimal.to_float() -> Result<f64, Error>

The nearest f64. Err(decimal::Error::OutOfRange) if the conversion fails.

# decimal.to_int() -> Result<i64, Error>

The value truncated towards zero. Err(decimal::Error::OutOfRange) if it doesn't fit in an i64.

┌ enum Error

A recoverable error from a `std::decimal` operation. Scripts can match the variant, e.g. `Err(decimal::Error::Parse(msg))`.

Error::OutOfRangeThe value does not fit the requested numeric type, or a float cannot be represented as a decimal.
Error::ParseThe string is not a valid decimal number.

> errors

decimal::Error is a matchable enum with two variants: OutOfRange (a value doesn't fit the requested type, or a float can't be represented as a decimal) and Parse (a string isn't a valid decimal).

> examples

use std::decimal;
use std::io;

fn main() -> Result<()> {
    let price = decimal::from_str("19.99")?;
    let qty = decimal::from_int(3);

    io::println("price = {}", price);
    io::println("rounded = {}", price.round());
    io::println("scale = {}", price.scale());

    Ok(())
}