### Configure bigdecimal-rs via environment variables Source: https://github.com/akubera/bigdecimal-rs/blob/trunk/README.md Examples of setting compile-time environment variables to control the behavior of BigDecimal operations, such as precision, rounding mode, and scientific notation thresholds. ```bash export BIG_DECIMAL_DEFAULT_PRECISION=8 cargo run export RUST_BIGDECIMAL_DEFAULT_PRECISION=5 cargo run export RUST_BIGDECIMAL_DEFAULT_ROUNDING_MODE=Down cargo run export RUST_BIGDECIMAL_EXPONENTIAL_FORMAT_THRESHOLD=2 cargo run ``` -------------------------------- ### Serialize BigDecimal with Serde Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Shows how to integrate BigDecimal with Serde for JSON serialization. Includes examples for both default string-based serialization and high-precision numeric serialization using the serde-json feature. ```rust use bigdecimal::BigDecimal; use serde::{Serialize, Deserialize}; use std::str::FromStr; #[derive(Debug, Serialize, Deserialize)] struct Transaction { id: String, amount: BigDecimal, #[serde(with = "bigdecimal::serde::json_num")] price: BigDecimal, } fn main() { let json_src = r#" { "id": "tx-001", "amount": "1234.5678", "price": 99.99 } "#; let tx: Transaction = serde_json::from_str(json_src).unwrap(); let output = serde_json::to_string(&tx).unwrap(); println!("{}", output); #[derive(Serialize, Deserialize)] struct Order { #[serde(with = "bigdecimal::serde::json_num_option")] discount: Option, } let order: Order = serde_json::from_str(r#"{"discount": null}"#).unwrap(); println!("discount: {:?}", order.discount); } ``` -------------------------------- ### Perform Basic Arithmetic with BigDecimal Source: https://github.com/akubera/bigdecimal-rs/blob/trunk/README.md Demonstrates importing the BigDecimal struct and calculating the square root of a number. ```rust use bigdecimal::BigDecimal; fn main() { let two = BigDecimal::from(2); println!("sqrt(2) = {}", two.sqrt().unwrap()); } ``` -------------------------------- ### Creating BigDecimal Values in Rust Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Demonstrates various methods for initializing BigDecimal values in Rust, including from strings (recommended for precision), integers, floating-point numbers, BigInt components, and using Zero/One traits. It highlights the importance of string parsing for exactness. ```rust use bigdecimal::BigDecimal; use std::str::FromStr; use bigdecimal::{FromPrimitive, Zero, One}; use bigdecimal::num_bigint::BigInt; // From string (recommended for exact precision) let from_str = BigDecimal::from_str("123.456789").unwrap(); // From integers let from_int = BigDecimal::from(42); let from_i64: BigDecimal = 1234567890i64.into(); // From floating-point (note: may have precision artifacts) let from_f64 = BigDecimal::from_f64(3.14159).unwrap(); let from_f32 = BigDecimal::from_f32(2.5).unwrap(); // From bytes let from_bytes = BigDecimal::parse_bytes(b"98765.4321", 10).unwrap(); // Using Zero and One traits let zero = BigDecimal::zero(); let one = BigDecimal::one(); // From BigInt with scale let digits = BigInt::from(123456); let decimal = BigDecimal::new(digits, 3); // 123.456 println!("from_str: {}", from_str); // 123.456789 println!("from_int: {}", from_int); // 42 println!("decimal: {}", decimal); // 123.456 ``` -------------------------------- ### Configure Serialization with Serde Source: https://github.com/akubera/bigdecimal-rs/blob/trunk/README.md Shows how to enable the serde-json feature in Cargo.toml and use the serde(with) attribute to serialize BigDecimal as a JSON number instead of a string. ```toml [dependencies] bigdecimal = { version = "0.4", features = [ "serde-json" ] } ``` ```rust use bigdecimal::BigDecimal; use serde::*; use serde_json; #[derive(Debug,Serialize,Deserialize)] struct MyStruct { name: String, value: BigDecimal, #[serde(with = "bigdecimal::serde::json_num")] number: BigDecimal, } fn main() { let json_src = r#" { "name": "foo", "value": 1234567e-3, "number": 3.14159 } "#; let my_struct: MyStruct = serde_json::from_str(&json_src).unwrap(); dbg!(my_struct); println!("{}", serde_json::to_string(&my_struct).unwrap()); } ``` -------------------------------- ### Configure Dependency in Cargo.toml Source: https://github.com/akubera/bigdecimal-rs/blob/trunk/README.md How to add the bigdecimal crate as a dependency in a Rust project's Cargo.toml file. ```toml [dependencies] bigdecimal = "0.4" ``` -------------------------------- ### Format BigDecimal Output in Rust Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Shows how to format BigDecimal objects into strings using standard display, scientific notation, engineering notation, and debug representations. ```rust use bigdecimal::BigDecimal; use std::str::FromStr; let n = BigDecimal::from_str("12345.6789").unwrap(); let large = BigDecimal::from(12345678); // Standard formatting println!("{:.2}", n); // 12345.68 // Scientific notation println!("{:e}", n); // 1.23456789e4 // Engineering notation println!("{}", large.to_engineering_notation()); // 12.345678e6 // Debug format println!("{:?}", n); ``` -------------------------------- ### Configure BigDecimal at Compile-Time Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Explains how to use environment variables to set default precision, rounding modes, and formatting thresholds for BigDecimal operations during compilation. ```rust use bigdecimal::BigDecimal; fn main() { let n = BigDecimal::from(700); // Result depends on compile-time RUST_BIGDECIMAL_DEFAULT_PRECISION println!("1/{} = {}", n, n.inverse()); } ``` -------------------------------- ### Perform inverse operation with bigdecimal-rs Source: https://github.com/akubera/bigdecimal-rs/blob/trunk/README.md Demonstrates basic usage of the BigDecimal library to calculate the inverse of a number. The output precision and rounding are determined by compile-time environment variables. ```rust fn main() { let n = BigDecimal::from(700); println!("1/{n} = {}", n.inverse()); } ``` -------------------------------- ### Inspect and Compare BigDecimal Values Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Demonstrates how to check signs, verify zero/one values, determine integer status, extract digits, and perform comparisons between BigDecimal instances. ```rust use bigdecimal::{BigDecimal, Signed, Zero, One}; use bigdecimal::num_bigint::Sign; use std::str::FromStr; let n = BigDecimal::from_str("-123.456").unwrap(); let zero = BigDecimal::zero(); let integer = BigDecimal::from_str("100.00").unwrap(); // Check sign println!("is_positive: {}", n.is_positive()); println!("is_negative: {}", n.is_negative()); println!("sign: {:?}", n.sign()); // Check for zero and one println!("is_zero: {}", zero.is_zero()); println!("is_one: {}", BigDecimal::one().is_one()); // Check if integer (no fractional part) println!("100.00 is_integer: {}", integer.is_integer()); println!("-123.456 is_integer: {}", n.is_integer()); // Get digit counts println!("digits: {}", n.digits()); println!("fractional_digit_count: {}", n.fractional_digit_count()); // Order of magnitude (floor of log10) let big = BigDecimal::from_str("9999").unwrap(); println!("order_of_magnitude: {}", big.order_of_magnitude()); // Extract components let (int_val, scale) = n.as_bigint_and_exponent(); println!("int_val: {}, scale: {}", int_val, scale); // Comparison let a = BigDecimal::from_str("1.0").unwrap(); let b = BigDecimal::from_str("1.00").unwrap(); let c = BigDecimal::from_str("2.0").unwrap(); println!("1.0 == 1.00: {}", a == b); println!("1.0 < 2.0: {}", a < c); println!("1.0.cmp(&2.0): {:?}", a.cmp(&c)); // Signum println!("signum(-123.456): {}", n.signum()); ``` -------------------------------- ### Perform efficient arithmetic with BigDecimalRef in Rust Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Demonstrates how to use BigDecimalRef to perform arithmetic and utility operations on borrowed BigDecimal values. This approach avoids cloning the underlying digit buffer, making it suitable for performance-sensitive applications. ```rust use bigdecimal::{BigDecimal, BigDecimalRef, Context}; use std::str::FromStr; use std::ops::Neg; fn add_one<'a, N: Into>>(n: N) -> BigDecimal { n.into() + 1 } fn main() { let n = BigDecimal::from_str("123.456").unwrap(); let n_ref = n.to_ref(); let result = add_one(&n); println!("123.456 + 1 = {}", result); let neg_ref = n.to_ref().neg(); let result = add_one(neg_ref); println!("-123.456 + 1 = {}", result); println!("sign: {:?}", n_ref.sign()); println!("is_zero: {}", n_ref.is_zero()); println!("count_digits: {}", n_ref.count_digits()); let owned = n_ref.to_owned(); println!("owned: {}", owned); let rescaled = n_ref.to_owned_with_scale(2); println!("scale 2: {}", rescaled); let ctx = Context::default().with_prec(5).unwrap(); let inverse = n_ref.inverse_with_context(&ctx); println!("1/n (5 digits): {}", inverse); let sqrt = n_ref.sqrt_with_context(&ctx); println!("sqrt(n) (5 digits): {}", sqrt.unwrap()); } ``` -------------------------------- ### Basic Arithmetic Operations with BigDecimal in Rust Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Illustrates standard arithmetic operations (addition, subtraction, multiplication, division, remainder, negation) on BigDecimal values in Rust using operator overloading. It shows how operations preserve precision and compound assignment operators. ```rust use bigdecimal::BigDecimal; use std::str::FromStr; let a = BigDecimal::from_str("10.5").unwrap(); let b = BigDecimal::from_str("3.2").unwrap(); // Addition let sum = &a + &b; println!("10.5 + 3.2 = {}", sum); // 13.7 // Subtraction let diff = &a - &b; println!("10.5 - 3.2 = {}", diff); // 7.3 // Multiplication (preserves all digits) let product = &a * &b; println!("10.5 * 3.2 = {}", product); // 33.60 // Division (uses default precision of 100 digits) let quotient = &a / &b; println!("10.5 / 3.2 = {}", quotient); // 3.28125 // Remainder let remainder = &a % &b; println!("10.5 % 3.2 = {}", remainder); // 0.9 // Negation let neg = -&a; println!("-10.5 = {}", neg); // -10.5 // Compound assignment operators let mut x = BigDecimal::from(100); x += BigDecimal::from(50); x -= BigDecimal::from(25); x *= BigDecimal::from(2); x /= BigDecimal::from(5); println!("Result: {}", x); // 50 ``` -------------------------------- ### Manage Precision and Rounding in Rust Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Demonstrates how to adjust precision and scale of BigDecimal values, apply specific rounding modes like HalfEven or Up, and normalize values by removing trailing zeros. ```rust use bigdecimal::{BigDecimal, RoundingMode}; use std::str::FromStr; let n = BigDecimal::from_str("129.41675").unwrap(); // Set precision (total significant digits) let prec_2 = n.with_prec(2); let prec_5 = n.with_prec(5); println!("with_prec(2): {}", prec_2); // 130 println!("with_prec(5): {}", prec_5); // 129.42 // Set scale (digits after decimal point) let scale_2 = n.with_scale(2); let scale_0 = n.with_scale(0); println!("with_scale(2): {}", scale_2); // 129.41 println!("with_scale(0): {}", scale_0); // 129 // Round with specific rounding mode let round_up = n.with_scale_round(2, RoundingMode::Up); let round_down = n.with_scale_round(2, RoundingMode::Down); let round_half_even = n.with_scale_round(4, RoundingMode::HalfEven); println!("Up: {}", round_up); // 129.42 println!("Down: {}", round_down); // 129.41 println!("HalfEven: {}", round_half_even); // 129.4168 // Default rounding (uses HalfEven by default) let rounded = n.round(2); println!("round(2): {}", rounded); // 129.42 // Normalize (remove trailing zeros) let trailing = BigDecimal::from_str("100.5000").unwrap(); println!("normalized: {}", trailing.normalized()); // 100.5 ``` -------------------------------- ### Mathematical Functions for BigDecimal in Rust Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Showcases advanced mathematical functions available for BigDecimal in Rust, including square root, cube root, powers, inverse, and exponential functions. It demonstrates configurable precision and rounding modes for these operations. ```rust use bigdecimal::BigDecimal; use std::str::FromStr; let n = BigDecimal::from(2); // Square root (returns Option, None for negative numbers) let sqrt_2 = n.sqrt().unwrap(); println!("sqrt(2) = {}", sqrt_2); // 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573 // Cube root let eight = BigDecimal::from(8); let cbrt_8 = eight.cbrt(); println!("cbrt(8) = {}", cbrt_8); // 2 // Square and cube (full precision, no rounding) let x = BigDecimal::from_str("1.5").unwrap(); println!("1.5² = {}", x.square()); // 2.25 println!("1.5³ = {}", x.cube()); // 3.375 // Integer powers let base = BigDecimal::from(2); println!("2^10 = {}", base.powi(10)); // 1024 // Inverse (reciprocal) let three = BigDecimal::from(3); let one_third = three.inverse(); println!("1/3 = {}", one_third); // 0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 // Exponential function e^x let one = BigDecimal::from(1); let e = one.exp(); println!("e = {}", e); // 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 // Double and half (efficient multiply/divide by 2) let val = BigDecimal::from_str("123.45").unwrap(); println!("double: {}", val.double()); // 246.90 println!("half: {}", val.half()); // 61.725 // Absolute value let negative = BigDecimal::from_str("-42.5").unwrap(); println!("abs(-42.5) = {}", negative.abs()); // 42.5 ``` -------------------------------- ### Perform Arithmetic with Context in Rust Source: https://context7.com/akubera/bigdecimal-rs/llms.txt Uses the Context struct to enforce specific precision and rounding rules during mathematical operations like multiplication, inversion, and square roots. ```rust use bigdecimal::{BigDecimal, Context, RoundingMode}; use std::str::FromStr; use std::num::NonZeroU64; let ctx5 = Context::default().with_prec(5).unwrap(); let x = BigDecimal::from_str("1.5").unwrap(); let y = BigDecimal::from_str("3.1415926535").unwrap(); // Multiplication with context let product = ctx5.multiply(&x, &y); println!("1.5 * π (5 digits) = {}", product); // 4.7124 // Square root with context let two = BigDecimal::from(2); let sqrt_ctx = two.sqrt_with_context(&ctx5); println!("sqrt(2) (5 digits) = {}", sqrt_ctx.unwrap()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.