Skip to main content

fastnum/decimal/
dec.rs

1//! # Signed Decimal
2
3mod cmp;
4mod construct;
5mod consts;
6mod control_block;
7mod convert;
8mod extra_precision;
9mod extras;
10mod format;
11mod impls;
12mod intrinsics;
13mod parse;
14mod resize;
15mod round;
16mod scale;
17mod truncate;
18
19pub(crate) mod math;
20pub(crate) mod utils;
21
22pub(crate) use control_block::ControlBlock;
23pub(crate) use extra_precision::ExtraPrecision;
24
25use core::{cmp::Ordering, fmt, num::FpCategory, panic};
26
27#[cfg(not(feature = "std"))]
28use alloc::{format, string::String};
29
30use crate::{
31    bint::UInt,
32    decimal,
33    decimal::{
34        dec::{consts::consts_impl, intrinsics::Intrinsics, math::consts::Consts, round::round},
35        doc,
36        signals::Signals,
37        Context, DecimalError, ParseError, RoundingMode, Sign, UnsignedDecimal,
38    },
39};
40
41/// # Decimal
42///
43/// Generic signed N-bits decimal number.
44#[derive(Copy, Clone)]
45#[repr(C)]
46pub struct Decimal<const N: usize> {
47    /// An N-bit unsigned integer coefficient. Represent significant decimal
48    /// digits.
49    digits: UInt<N>,
50
51    /// Control block
52    #[doc(hidden)]
53    cb: ControlBlock,
54}
55
56consts_impl!();
57
58impl<const N: usize> Decimal<N> {
59    /// Creates and initializes decimal from parts.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use fastnum::{*, decimal::*};
65    ///
66    /// assert_eq!(D256::from_parts(u256!(12345), -4, Sign::Minus, Context::default()), dec256!(-1.2345));
67    /// ```
68    #[track_caller]
69    #[must_use]
70    #[inline]
71    pub const fn from_parts(digits: UInt<N>, exp: i32, sign: Sign, ctx: Context) -> Self {
72        construct::construct(
73            digits,
74            exp,
75            sign,
76            Signals::empty(),
77            ctx,
78            ExtraPrecision::new(),
79        )
80        .check()
81    }
82
83    /// Creates and initializes decimal from string.
84    ///
85    /// # Examples
86    ///
87    /// ```
88    /// use fastnum::{*, decimal::*};
89    ///
90    /// assert_eq!(D256::from_str("-1.2345", Context::default()), Ok(dec256!(-1.2345)));
91    /// ```
92    #[track_caller]
93    #[inline]
94    pub const fn from_str(s: &str, ctx: Context) -> Result<Self, ParseError> {
95        parse::from_slice(s.as_bytes(), ctx)
96    }
97
98    /// Parse decimal from string.
99    ///
100    /// # Panics
101    ///
102    /// This function will panic if `Decimal<N>` can't be constructed
103    /// from a given string.
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// use fastnum::{*, decimal::*};
109    ///
110    /// assert_eq!(D256::parse_str("1.2345", Context::default()), dec256!(1.2345));
111    /// ```
112    ///
113    ///
114    /// ```should_panic
115    /// use fastnum::{*, decimal::*};
116    ///
117    /// let _ = D256::parse_str("Hello", Context::default());
118    /// ```
119    #[track_caller]
120    #[must_use]
121    #[inline]
122    pub const fn parse_str(s: &str, ctx: Context) -> Self {
123        match Self::from_str(s, ctx) {
124            Ok(n) => n,
125            Err(e) => {
126                panic!("{}", e.description())
127            }
128        }
129    }
130
131    /// Returns the internal big integer, representing the
132    /// [_Coefficient_](crate#representation) of a given `Decimal`, including
133    /// significant trailing zeros.
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use fastnum::{dec256, u256};
139    ///
140    /// let a = dec256!(-123.45);
141    /// assert_eq!(a.digits(), u256!(12345));
142    ///
143    /// let b = dec256!(-1.0);
144    /// assert_eq!(b.digits(), u256!(10));
145    /// ```
146    #[must_use]
147    #[inline(always)]
148    pub const fn digits(&self) -> UInt<N> {
149        self.digits
150    }
151
152    /// Return the count of digits in the non-scaled integer representation
153    #[must_use]
154    #[inline(always)]
155    pub const fn digits_count(&self) -> usize {
156        self.digits.decimal_digits() as usize
157    }
158
159    /// Return the scale of the `Decimal`, the total number of
160    /// digits to the right of the decimal point (including insignificant
161    /// leading zeros).
162    ///
163    /// # Examples:
164    ///
165    /// ```
166    /// use fastnum::dec256;
167    ///
168    /// let a = dec256!(12345);  // No fractional part
169    /// let b = dec256!(123.45);  // Fractional part
170    /// let c = dec256!(0.0000012345);  // Completely fractional part
171    /// let d = dec256!(500000000);  // No fractional part
172    /// let e = dec256!(5e9);  // Negative-fractional part
173    ///
174    /// assert_eq!(a.fractional_digits_count(), 0);
175    /// assert_eq!(b.fractional_digits_count(), 2);
176    /// assert_eq!(c.fractional_digits_count(), 10);
177    /// assert_eq!(d.fractional_digits_count(), 0);
178    /// assert_eq!(e.fractional_digits_count(), -9);
179    /// ```
180    #[must_use]
181    #[inline(always)]
182    pub const fn fractional_digits_count(&self) -> i16 {
183        self.cb.get_scale()
184    }
185
186    /// Return the sign of the `Decimal` as [Sign].
187    ///
188    /// # Examples
189    ///
190    /// ```
191    /// use fastnum::{decimal::Sign, dec256};
192    ///
193    /// assert_eq!(dec256!(-1.0).sign(), Sign::Minus);
194    /// assert_eq!(dec256!(0.0).sign(),  Sign::Plus);
195    /// assert_eq!(dec256!(+1.0).sign(),  Sign::Plus);
196    /// ```
197    #[must_use]
198    #[inline(always)]
199    pub const fn sign(&self) -> Sign {
200        self.cb.get_sign()
201    }
202
203    /// Returns `true` if the given decimal number is the result of division by
204    /// zero and `false` otherwise.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// use fastnum::{*, decimal::*};
210    ///
211    /// let ctx = Context::default().with_signal_traps(SignalsTraps::empty());
212    /// let res = dec256!(1.0).with_ctx(ctx) / dec256!(0).with_ctx(ctx);
213    ///
214    /// assert!(res.is_op_div_by_zero());
215    /// ```
216    ///
217    /// More about [`OP_DIV_BY_ZERO`](Signals::OP_DIV_BY_ZERO) signal.
218    #[must_use]
219    #[inline(always)]
220    pub const fn is_op_div_by_zero(&self) -> bool {
221        self.cb.is_signals_raised(Signals::OP_DIV_BY_ZERO)
222    }
223
224    /// Return `true` if the argument has [Signals::OP_OVERFLOW] signal flag,
225    /// and `false` otherwise.
226    #[must_use]
227    #[inline(always)]
228    pub const fn is_op_overflow(&self) -> bool {
229        self.cb.is_signals_raised(Signals::OP_OVERFLOW)
230    }
231
232    /// Return `true` if the argument has [Signals::OP_UNDERFLOW] signal flag,
233    /// and `false` otherwise.
234    #[must_use]
235    #[inline(always)]
236    pub const fn is_op_underflow(&self) -> bool {
237        self.cb.is_signals_raised(Signals::OP_UNDERFLOW)
238    }
239
240    /// Return `true` if the argument has [Signals::OP_INVALID] signal flag, and
241    /// `false` otherwise.
242    #[must_use]
243    #[inline(always)]
244    pub const fn is_op_invalid(&self) -> bool {
245        self.cb.is_signals_raised(Signals::OP_INVALID)
246    }
247
248    /// Return `true` if the argument has [Signals::OP_SUBNORMAL] signal flag,
249    /// and `false` otherwise.
250    #[must_use]
251    #[inline(always)]
252    pub const fn is_op_subnormal(&self) -> bool {
253        self.cb.is_signals_raised(Signals::OP_SUBNORMAL)
254    }
255
256    /// Return `true` if the argument has [Signals::OP_INEXACT] signal flag, and
257    /// `false` otherwise.
258    #[must_use]
259    #[inline(always)]
260    pub const fn is_op_inexact(&self) -> bool {
261        self.cb.is_signals_raised(Signals::OP_INEXACT)
262    }
263
264    /// Return `true` if the argument has [Signals::OP_ROUNDED] signal flag, and
265    /// `false` otherwise.
266    #[must_use]
267    #[inline(always)]
268    pub const fn is_op_rounded(&self) -> bool {
269        self.cb.is_signals_raised(Signals::OP_ROUNDED)
270    }
271
272    /// Return `true` if the argument has [Signals::OP_CLAMPED] signal flag, and
273    /// `false` otherwise.
274    #[must_use]
275    #[inline(always)]
276    pub const fn is_op_clamped(&self) -> bool {
277        self.cb.is_signals_raised(Signals::OP_CLAMPED)
278    }
279
280    /// Return `true` if the argument has no signal flags, and `false`
281    /// otherwise.
282    #[must_use]
283    #[inline(always)]
284    pub const fn is_op_ok(&self) -> bool {
285        self.cb.is_op_ok()
286    }
287
288    /// Return the [`signaling block`](Signals) of given decimal.
289    #[must_use]
290    #[inline(always)]
291    pub const fn op_signals(&self) -> Signals {
292        self.signals()
293    }
294
295    /// Return the decimal category of the number.
296    /// If only one property is going to be tested, it is generally faster to
297    /// use the specific predicate instead.
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// use core::num::FpCategory;
303    /// use fastnum::{dec256, D256};
304    ///
305    /// let num = dec256!(12.4);
306    /// let inf = D256::INFINITY;
307    ///
308    /// assert_eq!(num.classify(), FpCategory::Normal);
309    /// assert_eq!(inf.classify(), FpCategory::Infinite);
310    /// ```
311    #[must_use]
312    #[inline]
313    pub const fn classify(&self) -> FpCategory {
314        if self.cb.is_nan() {
315            FpCategory::Nan
316        } else if self.cb.is_infinity() {
317            FpCategory::Infinite
318        } else if self.digits.is_zero() {
319            FpCategory::Zero
320        } else if self.is_subnormal() {
321            FpCategory::Subnormal
322        } else {
323            FpCategory::Normal
324        }
325    }
326
327    /// Return `true` if the number is neither [zero], [`±Infinity`],
328    /// [subnormal], or [`NaN`] and `false` otherwise.
329    ///
330    /// # Examples
331    ///
332    /// ```
333    /// use fastnum::*;
334    ///
335    /// let num = dec256!(12.4);
336    /// let subnormal = dec256!(1E-30000) / dec256!(1E2768);
337    /// let inf = D256::INFINITY;
338    /// let nan = D256::NAN;
339    /// let zero = D256::ZERO;
340    ///
341    /// assert!(num.is_normal());
342    ///
343    /// assert!(!zero.is_normal());
344    /// assert!(!nan.is_normal());
345    /// assert!(!nan.is_normal());
346    /// assert!(!subnormal.is_normal());
347    /// ```
348    ///
349    /// [subnormal]: crate#normal-numbers-subnormal-numbers-and-underflow
350    /// [zero]: crate#signed-zero
351    /// [`±Infinity`]: crate#special-values
352    /// [`NaN`]: crate#special-values
353    #[must_use]
354    #[inline]
355    pub const fn is_normal(&self) -> bool {
356        matches!(self.classify(), FpCategory::Normal)
357    }
358
359    /// Return `true` if the number is [subnormal] and `false` otherwise.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// use fastnum::*;
365    ///
366    /// let num = dec256!(12.4);
367    /// let subnormal = dec256!(1E-30000) / dec256!(1E2768);
368    /// let inf = D256::INFINITY;
369    /// let nan = D256::NAN;
370    /// let zero = D256::ZERO;
371    ///
372    /// assert!(subnormal.is_subnormal());
373    ///
374    /// assert!(!num.is_subnormal());
375    /// assert!(!zero.is_subnormal());
376    /// assert!(!nan.is_subnormal());
377    /// assert!(!nan.is_subnormal());
378    /// ```
379    ///
380    /// [subnormal]: crate#normal-numbers-subnormal-numbers-and-underflow
381    #[must_use]
382    #[inline(always)]
383    pub const fn is_subnormal(&self) -> bool {
384        self.is_op_subnormal()
385    }
386
387    /// Return `true` if this number is neither [`±Infinity`] nor [`NaN`] and
388    /// `false` otherwise.
389    ///
390    /// # Examples
391    ///
392    /// ```
393    /// use fastnum::{D256, dec256};
394    ///
395    /// let d = dec256!(7.0);
396    /// let inf = D256::INFINITY;
397    /// let neg_inf = D256::NEG_INFINITY;
398    /// let nan = D256::NAN;
399    ///
400    /// assert!(d.is_finite());
401    ///
402    /// assert!(!nan.is_finite());
403    /// assert!(!inf.is_finite());
404    /// assert!(!neg_inf.is_finite());
405    /// ```
406    ///
407    /// [`±Infinity`]: crate#special-values
408    /// [`NaN`]: crate#special-values
409    #[must_use]
410    #[inline(always)]
411    pub const fn is_finite(&self) -> bool {
412        !self.cb.is_special()
413    }
414
415    /// Return `true` if this value is positive or negative [`Infinity`] and
416    /// `false` otherwise.
417    ///
418    /// # Examples
419    ///
420    /// ```
421    /// use fastnum::{D256, dec256};
422    ///
423    /// let d = dec256!(7.0);
424    /// let inf = D256::INFINITY;
425    /// let neg_inf = D256::NEG_INFINITY;
426    /// let nan = D256::NAN;
427    ///
428    /// assert!(inf.is_infinite());
429    /// assert!(neg_inf.is_infinite());
430    ///
431    /// assert!(!d.is_infinite());
432    /// assert!(!nan.is_infinite());
433    /// ```
434    ///
435    /// [`Infinity`]: crate#special-values
436    #[must_use]
437    #[inline(always)]
438    pub const fn is_infinite(&self) -> bool {
439        self.cb.is_infinity()
440    }
441
442    /// Return `true` if this value is [`NaN`] and `false` otherwise.
443    ///
444    /// # Examples
445    ///
446    /// ```
447    /// use fastnum::{D256, dec256};
448    ///
449    /// let nan = D256::NAN;
450    /// let d = dec256!(7.0);
451    ///
452    /// assert!(nan.is_nan());
453    /// assert!(!d.is_nan());
454    /// ```
455    ///
456    /// [`NaN`]: crate#special-values
457    #[must_use]
458    #[inline(always)]
459    pub const fn is_nan(&self) -> bool {
460        self.cb.is_nan()
461    }
462
463    /// Return `true` if this value is positive, including [`+0.0`],
464    /// [`+Infinity`] and [`NaN`], and `false` otherwise.
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// use fastnum::{D256, dec256};
470    ///
471    /// let d = dec256!(7.0);
472    /// let neg_zero = dec256!(-0.0);
473    /// let neg_d = dec256!(-7.0);
474    ///
475    /// assert!(d.is_sign_positive());
476    /// assert!(D256::ZERO.is_sign_positive());
477    /// assert!(D256::INFINITY.is_sign_positive());
478    /// assert!(D256::NAN.is_sign_positive());
479    ///
480    /// assert!(!neg_d.is_sign_positive());
481    /// assert!(!neg_zero.is_sign_positive());
482    /// assert!(!D256::NEG_INFINITY.is_sign_positive());
483    /// ```
484    ///
485    /// [`+0.0`]: crate#signed-zero
486    /// [`+Infinity`]: crate#special-values
487    /// [`NaN`]: crate#special-values
488    #[must_use]
489    #[inline(always)]
490    pub const fn is_sign_positive(&self) -> bool {
491        !self.cb.is_negative()
492    }
493
494    /// Return `true` if this value is negative, including [`-0.0`] and
495    /// [`-Infinity`] and `false` otherwise.
496    ///
497    /// # Examples
498    ///
499    /// ```
500    /// use fastnum::{D256, dec256};
501    ///
502    /// let d = dec256!(7.0);
503    /// let neg_zero = dec256!(-0.0);
504    /// let neg_d = dec256!(-7.0);
505    ///
506    /// assert!(neg_d.is_sign_negative());
507    /// assert!(neg_zero.is_sign_negative());
508    /// assert!(D256::NEG_INFINITY.is_sign_negative());
509    ///
510    /// assert!(!d.is_sign_negative());
511    /// assert!(!D256::ZERO.is_sign_negative());
512    /// assert!(!D256::INFINITY.is_sign_negative());
513    /// assert!(!D256::NAN.is_sign_negative());
514    /// ```
515    ///
516    /// [`-0.0`]: crate#signed-zero
517    /// [`-Infinity`]: crate#special-values
518    /// [`NaN`]: crate#special-values
519    #[must_use]
520    #[inline(always)]
521    pub const fn is_sign_negative(&self) -> bool {
522        self.cb.is_negative()
523    }
524
525    /// Return `true` if the referenced decimal is [`±0.0`] and `false`
526    /// otherwise.
527    ///
528    /// # Examples
529    ///
530    /// ```
531    /// use fastnum::*;
532    ///
533    /// let a = dec256!(0);
534    /// assert!(a.is_zero());
535    ///
536    /// let b = dec256!(0.0);
537    /// assert!(b.is_zero());
538    ///
539    /// let c = dec256!(-0.00);
540    /// assert!(c.is_zero());
541    ///
542    /// let d = dec256!(-0.1);
543    /// assert!(!d.is_zero());
544    /// ```
545    ///
546    /// [`±0.0`]: crate#signed-zero
547    #[must_use]
548    #[inline(always)]
549    pub const fn is_zero(&self) -> bool {
550        self.digits.is_zero() && !self.cb.is_special() && !self.cb.has_extra_precision()
551    }
552
553    /// Return `true` if the referenced decimal is strictly `1` and `false`
554    /// otherwise.
555    ///
556    /// # Examples
557    ///
558    /// ```
559    /// use fastnum::*;
560    ///
561    /// let a = dec256!(1);
562    /// assert!(a.is_one());
563    ///
564    /// let b = dec256!(10e-1);
565    /// assert!(!b.is_one());
566    /// ```
567    #[must_use]
568    #[inline(always)]
569    pub const fn is_one(&self) -> bool {
570        self.digits.is_one()
571            && self.cb.get_scale() == 0
572            && !self.cb.is_negative()
573            && !self.cb.is_special()
574            && !self.cb.has_extra_precision()
575    }
576
577    /// Return `true` if this value is positive, including [`+0.0`],
578    /// [`+Infinity`] and [`NaN`], and `false` otherwise.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use fastnum::*;
584    ///
585    /// let d = dec256!(7.0);
586    /// let neg_zero = dec256!(-0.0);
587    /// let neg_d = dec256!(-7.0);
588    ///
589    /// assert!(d.is_positive());
590    /// assert!(D256::ZERO.is_positive());
591    /// assert!(D256::INFINITY.is_positive());
592    /// assert!(D256::NAN.is_positive());
593    ///
594    /// assert!(!neg_d.is_positive());
595    /// assert!(!neg_zero.is_positive());
596    /// assert!(!D256::NEG_INFINITY.is_positive());
597    /// ```
598    ///
599    /// [`+0.0`]: crate#signed-zero
600    /// [`+Infinity`]: crate#special-values
601    /// [`NaN`]: crate#special-values
602    #[must_use]
603    #[inline(always)]
604    pub const fn is_positive(&self) -> bool {
605        !self.cb.is_negative()
606    }
607
608    /// Return `true` if this value is negative, including [`-0.0`] and
609    /// [`-Infinity`] and `false` otherwise.
610    ///
611    /// # Examples
612    ///
613    /// ```
614    /// use fastnum::*;
615    ///
616    /// let d = dec256!(7.0);
617    /// let neg_zero = dec256!(-0.0);
618    /// let neg_d = dec256!(-7.0);
619    ///
620    /// assert!(neg_d.is_negative());
621    /// assert!(neg_zero.is_negative());
622    /// assert!(D256::NEG_INFINITY.is_negative());
623    ///
624    /// assert!(!d.is_negative());
625    /// assert!(!D256::ZERO.is_negative());
626    /// assert!(!D256::INFINITY.is_negative());
627    /// assert!(!D256::NAN.is_negative());
628    /// ```
629    ///
630    /// [`-0.0`]: crate#signed-zero
631    /// [`-Infinity`]: crate#special-values
632    /// [`NaN`]: crate#special-values
633    #[must_use]
634    #[inline(always)]
635    pub const fn is_negative(&self) -> bool {
636        self.cb.is_negative()
637    }
638
639    #[doc = doc::with_ctx::with_ctx!(256)]
640    #[must_use = doc::must_use_op!()]
641    #[inline(always)]
642    pub const fn with_ctx(self, ctx: Context) -> Self {
643        self.set_ctx(ctx).round_extra_precision().check()
644    }
645
646    #[doc = doc::with_rounding_mode::with_rounding_mode!(256)]
647    #[must_use = doc::must_use_op!()]
648    #[inline(always)]
649    pub const fn with_rounding_mode(self, rm: RoundingMode) -> Self {
650        self.set_rounding_mode(rm).round_extra_precision().check()
651    }
652
653    /// Invert the sign of the given decimal.
654    ///
655    /// # Examples
656    ///
657    /// ```
658    /// use fastnum::dec256;
659    ///
660    /// assert_eq!(dec256!(+1.0).neg(), dec256!(-1.0));
661    /// assert_eq!(dec256!(1.0).neg(), dec256!(-1.0));
662    /// assert_eq!(dec256!(-1.0).neg(), dec256!(1.0));
663    /// ```
664    #[must_use]
665    #[inline(always)]
666    pub const fn neg(mut self) -> Self {
667        self.cb.neg();
668        self
669    }
670
671    /// Get the absolute value of the decimal (non-negative sign).
672    ///
673    /// # Examples
674    ///
675    /// ```
676    /// use fastnum::dec256;
677    ///
678    /// assert_eq!(dec256!(1.0).abs(), dec256!(1.0));
679    /// assert_eq!(dec256!(-1.0).abs(), dec256!(1.0));
680    /// ```
681    #[must_use]
682    #[inline(always)]
683    pub const fn abs(self) -> Self {
684        math::abs::abs(self).check()
685    }
686
687    /// Get the absolute value of the decimal (non-negative sign) as
688    /// [UnsignedDecimal].
689    ///
690    /// # Examples
691    ///
692    /// ```
693    /// use fastnum::{dec256, udec256};
694    ///
695    /// assert_eq!(dec256!(1.0).unsigned_abs(), udec256!(1.0));
696    /// assert_eq!(dec256!(-1.0).unsigned_abs(), udec256!(1.0));
697    /// ```
698    #[must_use]
699    #[inline]
700    pub const fn unsigned_abs(self) -> UnsignedDecimal<N> {
701        UnsignedDecimal::new(self.abs())
702    }
703
704    /// The quantum of a finite number is given by: 1 × 10<sup>exp</sup>.
705    /// This is the value of a unit in the least significant position of the
706    /// coefficient of a finite number.
707    ///
708    /// # Examples
709    ///
710    /// ```
711    /// use fastnum::{D256, dec256, decimal::Context};
712    ///
713    /// let ctx = Context::default();
714    ///
715    /// assert_eq!(D256::quantum(0, ctx), dec256!(1));
716    /// assert_eq!(D256::quantum(-0, ctx), dec256!(1));
717    /// assert_eq!(D256::quantum(-3, ctx), dec256!(0.001));
718    /// assert_eq!(D256::quantum(3, ctx), dec256!(1000));
719    /// ```
720    #[must_use]
721    #[track_caller]
722    #[inline]
723    pub const fn quantum(exp: i32, ctx: Context) -> Self {
724        scale::quantum(exp, ctx).check()
725    }
726
727    /// Returns a number that represents the sign of `self`.
728    ///
729    /// - `1.0` if the number is positive, `+0.0` or
730    ///   [`INFINITY`](Self::INFINITY)
731    /// - `-1.0` if the number is negative, `-0.0` or
732    ///   [`NEG_INFINITY`](Self::NEG_INFINITY)
733    /// - [`NAN`](Self::NAN) if the number is [`NAN`](Self::NAN)
734    ///
735    /// ```
736    /// use fastnum::{D256, dec256};
737    ///
738    /// let d = dec256!(3.5);
739    ///
740    /// assert_eq!(d.signum(), dec256!(1.0));
741    /// assert_eq!(D256::NEG_INFINITY.signum(), dec256!(-1.0));
742    ///
743    /// assert!(D256::NAN.signum().is_nan());
744    /// ```
745    #[must_use]
746    #[inline]
747    pub const fn signum(&self) -> Self {
748        if self.is_nan() {
749            Self::NAN
750        } else if self.is_negative() {
751            Self::ONE.neg()
752        } else {
753            Self::ONE
754        }
755    }
756
757    /// Reduces a decimal number to its shortest (coefficient)
758    /// form shifting all significant trailing zeros into the exponent.
759    ///
760    /// # Examples
761    ///
762    /// ```
763    /// use fastnum::*;
764    ///
765    /// let a = dec256!(-1234500);
766    /// assert_eq!(a.digits(), u256!(1234500));
767    /// assert_eq!(a.fractional_digits_count(), 0);
768    ///
769    /// let b = a.reduce();
770    /// assert_eq!(b.digits(), u256!(12345));
771    /// assert_eq!(b.fractional_digits_count(), -2);
772    /// ```
773    #[must_use = doc::must_use_op!()]
774    #[track_caller]
775    #[inline]
776    pub const fn reduce(self) -> Self {
777        scale::reduce(self).check()
778    }
779
780    /// Tests for `self` and `other` values to be equal, and is used by `==`
781    /// operator.
782    #[must_use]
783    #[inline(always)]
784    pub const fn eq(&self, other: &Self) -> bool {
785        cmp::eq(self, other)
786    }
787
788    /// Tests for `self` and `other` values to be equal, and is used by `==`
789    /// operator.
790    #[must_use]
791    #[inline(always)]
792    pub const fn ne(&self, other: &Self) -> bool {
793        cmp::ne(self, other)
794    }
795
796    /// Compares and returns the maximum of two signed decimal values.
797    ///
798    /// Returns the second argument if the comparison determines them to be
799    /// equal.
800    ///
801    /// # Examples
802    ///
803    /// ```
804    /// use fastnum::{dec256};
805    ///
806    /// assert_eq!(dec256!(1).max(dec256!(2)), dec256!(2));
807    /// assert_eq!(dec256!(2).max(dec256!(2)), dec256!(2));
808    /// ```
809    #[must_use]
810    #[inline]
811    pub const fn max(self, other: Self) -> Self {
812        match self.cmp(&other) {
813            Ordering::Less | Ordering::Equal => other,
814            _ => self,
815        }
816    }
817
818    /// Compares and returns the minimum of two signed decimal values.
819    ///
820    /// Returns the first argument if the comparison determines them to be
821    /// equal.
822    ///
823    /// # Examples
824    ///
825    /// ```
826    /// use fastnum::dec256;
827    ///
828    /// assert_eq!(dec256!(1).min(dec256!(2)), dec256!(1));
829    /// assert_eq!(dec256!(2).min(dec256!(2)), dec256!(2));
830    /// ```
831    #[must_use]
832    #[inline]
833    pub const fn min(self, other: Self) -> Self {
834        match self.cmp(&other) {
835            Ordering::Less | Ordering::Equal => self,
836            _ => other,
837        }
838    }
839
840    /// Restrict a signed decimal value to a certain interval.
841    ///
842    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
843    /// less than `min`. Otherwise, this returns `self`.
844    ///
845    /// # Panics
846    ///
847    /// Panics if `min > max`.
848    ///
849    /// # Examples
850    ///
851    /// ```
852    /// use fastnum::dec256;
853    ///
854    /// assert_eq!(dec256!(-3).clamp(dec256!(-2), dec256!(1)), dec256!(-2));
855    /// assert_eq!(dec256!(0).clamp(dec256!(-2), dec256!(1)), dec256!(0));
856    /// assert_eq!(dec256!(2).clamp(dec256!(-2), dec256!(1)), dec256!(1));
857    /// ```
858    #[must_use]
859    #[inline]
860    pub const fn clamp(self, min: Self, max: Self) -> Self {
861        assert!(min.le(&max));
862        if let Ordering::Less = self.cmp(&min) {
863            min
864        } else if let Ordering::Greater = self.cmp(&max) {
865            max
866        } else {
867            self
868        }
869    }
870
871    /// The positive difference of two decimal numbers.
872    ///
873    /// # Examples
874    ///
875    /// * If `self <= other`: `0:0`
876    /// * Else: `self - other`
877    ///
878    /// ```
879    /// use fastnum::dec256;
880    ///
881    /// assert_eq!(dec256!(1).abs_sub(dec256!(3)), dec256!(0));
882    /// assert_eq!(dec256!(3).abs_sub(dec256!(1)), dec256!(2));
883    /// ```
884    #[must_use]
885    #[inline]
886    pub const fn abs_sub(self, other: Self) -> Self {
887        if self.le(&other) {
888            Self::ZERO
889        } else {
890            math::sub::sub(self, other)
891        }
892    }
893
894    /// Tests signed decimal `self` less than `other` and is used by the `<`
895    /// operator.
896    ///
897    /// # Examples
898    ///
899    /// ```
900    /// use fastnum::dec256;
901    ///
902    /// assert_eq!(dec256!(1.0).lt(&dec256!(1.0)), false);
903    /// assert_eq!(dec256!(1.0).lt(&dec256!(2.0)), true);
904    /// assert_eq!(dec256!(2.0).lt(&dec256!(1.0)), false);
905    /// ```
906    #[must_use]
907    #[inline(always)]
908    pub const fn lt(&self, other: &Self) -> bool {
909        matches!(self.cmp(other), Ordering::Less)
910    }
911
912    /// Tests signed decimal `self` less than or equal to `other` and is used by
913    /// the `<=` operator.
914    ///
915    /// # Examples
916    ///
917    /// ```
918    /// use fastnum::dec256;
919    ///
920    /// assert_eq!(dec256!(1.0).le(&dec256!(1.0)), true);
921    /// assert_eq!(dec256!(1.0).le(&dec256!(2.0)), true);
922    /// assert_eq!(dec256!(2.0).le(&dec256!(1.0)), false);
923    /// ```
924    #[must_use]
925    #[inline(always)]
926    pub const fn le(&self, other: &Self) -> bool {
927        matches!(self.cmp(other), Ordering::Less | Ordering::Equal)
928    }
929
930    /// Tests signed decimal `self` greater than `other` and is used by the `>`
931    /// operator.
932    ///
933    /// # Examples
934    ///
935    /// ```
936    /// use fastnum::dec256;
937    ///
938    /// assert_eq!(dec256!(1.0).gt(&dec256!(1.0)), false);
939    /// assert_eq!(dec256!(1.0).gt(&dec256!(2.0)), false);
940    /// assert_eq!(dec256!(2.0).gt(&dec256!(1.0)), true);
941    /// ```
942    #[must_use]
943    #[inline(always)]
944    pub const fn gt(&self, other: &Self) -> bool {
945        matches!(self.cmp(other), Ordering::Greater)
946    }
947
948    /// Tests signed decimal `self` greater than or equal to `other` and is used
949    /// by the `>=` operator.
950    ///
951    /// # Examples
952    ///
953    /// ```
954    /// use fastnum::dec256;
955    ///
956    /// assert_eq!(dec256!(1.0).ge(&dec256!(1.0)), true);
957    /// assert_eq!(dec256!(1.0).ge(&dec256!(2.0)), false);
958    /// assert_eq!(dec256!(2.0).ge(&dec256!(1.0)), true);
959    /// ```
960    #[must_use]
961    #[inline(always)]
962    pub const fn ge(&self, other: &Self) -> bool {
963        matches!(self.cmp(other), Ordering::Greater | Ordering::Equal)
964    }
965
966    /// This method returns an [`Ordering`] between `self` and `other`.
967    ///
968    /// By convention, `self.cmp(&other)` returns the ordering matching the
969    /// expression `self <operator> other` if true.
970    ///
971    /// # Examples
972    ///
973    /// ```
974    /// use fastnum::dec256;
975    /// use std::cmp::Ordering;
976    ///
977    /// assert_eq!(dec256!(5).cmp(&dec256!(10)), Ordering::Less);
978    /// assert_eq!(dec256!(10).cmp(&dec256!(5)), Ordering::Greater);
979    /// assert_eq!(dec256!(5).cmp(&dec256!(5)), Ordering::Equal);
980    /// ```
981    #[must_use]
982    #[inline(always)]
983    pub const fn cmp(&self, other: &Self) -> Ordering {
984        cmp::cmp(self, other)
985    }
986
987    /// Calculates `self` + `rhs`.
988    ///
989    /// Is internally used by the `+` operator.
990    ///
991    /// # Panics:
992    #[doc = doc::decimal_operation_panics!("addition operation")]
993    /// # Examples
994    ///
995    /// Basic usage:
996    ///
997    /// ```
998    /// use fastnum::*;
999    ///
1000    /// let a = D256::ONE;
1001    /// let b = D256::TWO;
1002    ///
1003    /// let c = a + b;
1004    /// assert_eq!(c, dec256!(3));
1005    /// ```
1006    ///
1007    /// Panics if overflowed:
1008    ///
1009    /// ```should_panic
1010    /// use fastnum::*;
1011    ///
1012    /// let a = D256::MAX;
1013    /// let b = D256::MAX;
1014    ///
1015    /// let c = a + b;
1016    /// ```
1017    ///
1018    /// See more about [add and subtract](crate#addition-and-subtraction).
1019    #[must_use = doc::must_use_op!()]
1020    #[track_caller]
1021    #[inline(always)]
1022    pub const fn add(self, rhs: Self) -> Self {
1023        math::add::add(self, rhs).round_extra_precision().check()
1024    }
1025
1026    /// Calculates `self` – `rhs`.
1027    ///
1028    /// Is internally used by the `-` operator.
1029    ///
1030    /// # Panics:
1031    #[doc = doc::decimal_operation_panics!("subtract operation")]
1032    /// # Examples
1033    ///
1034    /// Basic usage:
1035    ///
1036    /// ```
1037    /// use fastnum::*;
1038    ///
1039    /// let a = D256::ONE;
1040    /// let b = D256::TWO;
1041    ///
1042    /// let c = a - b;
1043    /// assert_eq!(c, dec256!(-1));
1044    /// ```
1045    ///
1046    /// Panics if overflowed:
1047    ///
1048    /// ```should_panic
1049    /// use fastnum::*;
1050    ///
1051    /// let a = D256::MAX;
1052    /// let b = -D256::MAX;
1053    ///
1054    /// let c = a - b;
1055    /// ```
1056    /// See more about [add and subtract](crate#addition-and-subtraction).
1057    #[must_use = doc::must_use_op!()]
1058    #[track_caller]
1059    #[inline(always)]
1060    pub const fn sub(self, rhs: Self) -> Self {
1061        math::sub::sub(self, rhs).round_extra_precision().check()
1062    }
1063
1064    /// Calculates `self` × `rhs`.
1065    ///
1066    /// Is internally used by the `*` operator.
1067    ///
1068    /// # Panics:
1069    #[doc = doc::decimal_operation_panics!("multiplication operation")]
1070    /// # Examples
1071    ///
1072    /// Basic usage:
1073    ///
1074    /// ```
1075    /// use fastnum::*;
1076    ///
1077    /// let a = D256::FIVE;
1078    /// let b = D256::TWO;
1079    ///
1080    /// let c = a * b;
1081    /// assert_eq!(c, dec256!(10));
1082    /// ```
1083    ///
1084    /// Panics if overflowed:
1085    ///
1086    /// ```should_panic
1087    /// use fastnum::*;
1088    ///
1089    /// let a = D256::MAX;
1090    /// let b = D256::MAX;
1091    ///
1092    /// let c = a * b;
1093    /// ```
1094    ///
1095    /// See more about [multiplication](crate#multiplication).
1096    #[must_use = doc::must_use_op!()]
1097    #[track_caller]
1098    #[inline(always)]
1099    pub const fn mul(self, rhs: Self) -> Self {
1100        math::mul::mul(self, rhs).round_extra_precision().check()
1101    }
1102
1103    /// Calculates `self` ÷ `rhs`.
1104    ///
1105    /// Is internally used by the `/` operator.
1106    ///
1107    /// # Panics:
1108    #[doc = doc::decimal_operation_panics!("divide operation")]
1109    /// # Examples
1110    ///
1111    /// Basic usage:
1112    ///
1113    /// ```
1114    /// use fastnum::*;
1115    ///
1116    /// let a = D256::FIVE;
1117    /// let b = D256::TWO;
1118    ///
1119    /// let c = -a / b;
1120    /// assert_eq!(c, dec256!(-2.5));
1121    /// ```
1122    ///
1123    /// Panics if divided by zero:
1124    ///
1125    /// ```should_panic
1126    /// use fastnum::{dec256, D256};
1127    ///
1128    /// let a = D256::ONE;
1129    /// let b = D256::ZERO;
1130    ///
1131    /// let c = a / b;
1132    /// ```
1133    ///
1134    /// See more about [division](crate#division).
1135    #[must_use = doc::must_use_op!()]
1136    #[track_caller]
1137    #[inline(always)]
1138    pub const fn div(self, rhs: Self) -> Self {
1139        math::div::div(self, rhs).round_extra_precision().check()
1140    }
1141
1142    /// Calculates `self` % `rhs`.
1143    ///
1144    /// Is internally used by the `%` operator.
1145    ///
1146    /// # Panics:
1147    #[doc = doc::decimal_operation_panics!("reminder operation")]
1148    /// # Examples
1149    ///
1150    /// Basic usage:
1151    ///
1152    /// ```
1153    /// use fastnum::*;
1154    ///
1155    /// let a = D256::FIVE;
1156    /// let b = D256::TWO;
1157    ///
1158    /// let c = a % b;
1159    /// assert_eq!(c, dec256!(1));
1160    /// ```
1161    #[must_use = doc::must_use_op!()]
1162    #[track_caller]
1163    #[inline(always)]
1164    pub const fn rem(self, rhs: Self) -> Self {
1165        math::rem::rem(self, rhs).round_extra_precision().check()
1166    }
1167
1168    /// Raise a decimal number to decimal power.
1169    ///
1170    /// Using this function is generally slower than using `powi` for integer
1171    /// powers or `sqrt` method for `1/2` exponent.
1172    #[doc = doc::decimal_inexact!("power operation")]
1173    /// # Panics:
1174    #[doc = doc::decimal_operation_panics!("power operation")]
1175    /// # Examples
1176    ///
1177    /// Basic usage:
1178    ///
1179    /// ```
1180    /// use fastnum::*;
1181    ///
1182    /// assert_eq!(dec256!(4).pow(dec256!(0.5)), dec256!(2));
1183    /// assert_eq!(dec256!(8).pow(dec256!(1) / dec256!(3)), dec256!(2));
1184    /// ```
1185    ///
1186    /// See more about the [power](crate#power) operation.
1187    #[must_use = doc::must_use_op!()]
1188    #[track_caller]
1189    #[inline]
1190    pub const fn pow(self, n: Self) -> Self {
1191        math::pow::pow(self, n).round_extra_precision().check()
1192    }
1193
1194    /// Raise a decimal number to an integer power.
1195    ///
1196    /// Using this function is generally faster than using `pow`
1197    ///
1198    /// # Panics:
1199    #[doc = doc::decimal_operation_panics!("power operation")]
1200    /// # Examples
1201    ///
1202    /// Basic usage:
1203    ///
1204    /// ```
1205    /// use fastnum::*;
1206    ///
1207    /// assert_eq!(dec256!(2).powi(3), dec256!(8));
1208    /// assert_eq!(dec256!(9).powi(2), dec256!(81));
1209    /// assert_eq!(dec256!(1).powi(-2), dec256!(1));
1210    /// assert_eq!(dec256!(10).powi(20), dec256!(1e20));
1211    /// assert_eq!(dec256!(4).powi(-2), dec256!(0.0625));
1212    /// ```
1213    ///
1214    /// See more about the [power](crate#power) operation.
1215    #[must_use = doc::must_use_op!()]
1216    #[track_caller]
1217    #[inline]
1218    pub const fn powi(self, n: i32) -> Self {
1219        math::powi::powi(self, n).round_extra_precision().check()
1220    }
1221
1222    /// Take the square root of the decimal number using
1223    /// [Heron's method](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Heron's_method),
1224    /// a special case of [Newton's](https://en.wikipedia.org/wiki/Newton%27s_method) method.
1225    ///
1226    /// Returns [`NaN`](crate#nan) if `self` is a negative number other than
1227    /// `-0.0`.
1228    #[doc = doc::decimal_inexact!("square root operation")]
1229    /// # Panics:
1230    #[doc = doc::decimal_operation_panics!("square root operation")]
1231    /// # Examples
1232    ///
1233    /// Basic usage:
1234    ///
1235    /// ```
1236    /// use fastnum::*;
1237    ///
1238    /// assert_eq!(dec128!(4).sqrt(), dec128!(2));
1239    /// assert_eq!(dec128!(1).sqrt(), dec128!(1));
1240    /// assert_eq!(dec128!(16).sqrt(), dec128!(4));
1241    /// assert_eq!(dec128!(2).sqrt(), D128::SQRT_2);
1242    /// ```
1243    ///
1244    /// See more about the [square-root](crate#square-root) operation.
1245    #[must_use = doc::must_use_op!()]
1246    #[track_caller]
1247    #[inline]
1248    pub const fn sqrt(self) -> Self {
1249        math::sqrt::sqrt(self).round_extra_precision().check()
1250    }
1251
1252    /// Take the cubic root of a decimal number using
1253    /// [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method).
1254    #[doc = doc::decimal_inexact!("cubic root operation")]
1255    /// # Panics:
1256    #[doc = doc::decimal_operation_panics!("cubic root operation")]
1257    /// # Examples
1258    ///
1259    /// Basic usage:
1260    ///
1261    /// ```
1262    /// use fastnum::*;
1263    ///
1264    /// assert_eq!(dec128!(8).cbrt(), dec128!(2));
1265    /// ```
1266    ///
1267    /// See more about the [N-th root](crate#n-th-roots) operation.
1268    #[must_use = doc::must_use_op!()]
1269    #[track_caller]
1270    #[inline]
1271    pub const fn cbrt(self) -> Self {
1272        math::cbrt::cbrt(self).round_extra_precision().check()
1273    }
1274
1275    /// Take the N-th root of the decimal number using
1276    /// [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method).
1277    #[doc = doc::decimal_inexact!("N-th root operation")]
1278    /// # Panics:
1279    #[doc = doc::decimal_operation_panics!("N-th root operation")]
1280    /// # Examples
1281    ///
1282    /// Basic usage:
1283    ///
1284    /// ```
1285    /// use fastnum::*;
1286    ///
1287    /// assert_eq!(dec128!(16).nth_root(4), dec128!(2));
1288    /// ```
1289    ///
1290    /// See more about the [N-th root](crate#n-th-roots) operation.
1291    #[must_use = doc::must_use_op!()]
1292    #[track_caller]
1293    #[inline]
1294    pub const fn nth_root(self, n: u32) -> Self {
1295        math::nth_root::nth_root(self, n)
1296            .round_extra_precision()
1297            .check()
1298    }
1299
1300    /// Returns _e<sup>self</sup>_, (the exponential function).
1301    #[doc = doc::decimal_inexact!("exponential function")]
1302    /// # Panics:
1303    #[doc = doc::decimal_operation_panics!("exponent calculation")]
1304    /// # Examples
1305    ///
1306    /// Basic usage:
1307    ///
1308    /// ```
1309    /// use fastnum::*;
1310    ///
1311    /// assert_eq!(dec128!(1).exp(), D128::E);
1312    /// ```
1313    ///
1314    /// See more about the [exponential function](crate#exponential-function).
1315    #[must_use = doc::must_use_op!()]
1316    #[track_caller]
1317    #[inline]
1318    pub const fn exp(self) -> Self {
1319        math::exp::exp(self).round_extra_precision().check()
1320    }
1321
1322    /// Returns _e<sup>self</sup> – 1_.
1323    #[doc = doc::decimal_inexact!("exponential function")]
1324    /// # Panics:
1325    #[doc = doc::decimal_operation_panics!("exponent calculation")]
1326    /// # Examples
1327    ///
1328    /// Basic usage:
1329    ///
1330    /// ```
1331    /// use fastnum::{*, decimal::RoundingMode::*};
1332    ///
1333    /// // For exact result we need to use extra precision digits and no-rounding mode to keep precision between `.ln()` and `exp()` calls.
1334    /// // Than we can use default rounding mode for round extra digits.
1335    /// assert_eq!(dec128!(7.0).with_rounding_mode(No).ln().exp_m1().with_rounding_mode(HalfUp), D128::SIX);
1336    /// ```
1337    ///
1338    /// See more about the [exponential function](crate#exponential-function).
1339    #[must_use = doc::must_use_op!()]
1340    #[inline]
1341    pub const fn exp_m1(self) -> Self {
1342        math::exp::exp_m1(self).round_extra_precision().check()
1343    }
1344
1345    /// Returns _2<sup>self</sup>_, (the binary exponential function).
1346    #[doc = doc::decimal_inexact!("binary exponential function")]
1347    /// # Panics:
1348    #[doc = doc::decimal_operation_panics!("binary exponential function")]
1349    /// # Examples
1350    ///
1351    /// Basic usage:
1352    ///
1353    /// ```
1354    /// use fastnum::*;
1355    ///
1356    /// assert_eq!(dec128!(0).exp2(), dec128!(1));
1357    /// assert_eq!(dec128!(1).exp2(), dec128!(2));
1358    /// assert_eq!(dec128!(2).exp2(), dec128!(4));
1359    /// assert_eq!(dec128!(3).exp2(), dec128!(8));
1360    /// ```
1361    /// See more about the [binary exponential
1362    /// function](crate#binary-exponential-function).
1363    #[must_use = doc::must_use_op!()]
1364    #[track_caller]
1365    #[inline]
1366    pub const fn exp2(self) -> Self {
1367        math::exp2::exp2(self).round_extra_precision().check()
1368    }
1369
1370    #[doc = doc::log::ln!(256)]
1371    #[must_use = doc::must_use_op!()]
1372    #[inline(always)]
1373    pub const fn ln(self) -> Self {
1374        math::log::ln(self).round_extra_precision().check()
1375    }
1376
1377    #[doc = doc::log::ln_1p!(256)]
1378    #[must_use = doc::must_use_op!()]
1379    #[inline(always)]
1380    pub const fn ln_1p(self) -> Self {
1381        math::log::ln_1p(self).round_extra_precision().check()
1382    }
1383
1384    #[doc = doc::log::log!(256)]
1385    #[must_use = doc::must_use_op!()]
1386    #[inline(always)]
1387    pub const fn log(self, base: Self) -> Self {
1388        math::log::log(self, base).round_extra_precision().check()
1389    }
1390
1391    #[doc = doc::log::log2!(256)]
1392    #[must_use = doc::must_use_op!()]
1393    #[inline(always)]
1394    pub const fn log2(self) -> Self {
1395        math::log::log2(self).round_extra_precision().check()
1396    }
1397
1398    #[doc = doc::log::log10!(256)]
1399    #[must_use = doc::must_use_op!()]
1400    #[inline(always)]
1401    pub const fn log10(self) -> Self {
1402        math::log::log10(self).round_extra_precision().check()
1403    }
1404
1405    /// Calculate the length of the hypotenuse of a right-angle triangle given
1406    /// legs of length `x` and `y`.
1407    ///
1408    /// # Panics:
1409    #[doc = doc::decimal_operation_panics!("hypotenuse calculate operation")]
1410    /// # Examples
1411    ///
1412    /// Basic usage:
1413    ///
1414    /// ```
1415    /// use fastnum::dec256;
1416    ///
1417    /// let x = dec256!(2);
1418    /// let y = dec256!(3);
1419    ///
1420    /// // sqrt(x^2 + y^2)
1421    /// assert_eq!(x.hypot(y), (x.powi(2) + y.powi(2)).sqrt());
1422    /// ```
1423    #[must_use = doc::must_use_op!()]
1424    #[track_caller]
1425    #[inline]
1426    pub const fn hypot(self, other: Self) -> Self {
1427        math::hypot::hypot(self, other)
1428            .round_extra_precision()
1429            .check()
1430    }
1431
1432    /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1433    /// error, yielding a more accurate result than an unfused multiply-add.
1434    ///
1435    /// # Panics:
1436    #[doc = doc::decimal_operation_panics!("multiply-add operation")]
1437    /// # Examples
1438    ///
1439    /// Basic usage:
1440    ///
1441    /// ```
1442    /// use fastnum::*;
1443    ///
1444    /// assert_eq!(dec128!(10.0).mul_add(dec128!(4.0), dec128!(60)), dec128!(100));
1445    /// ```
1446    ///
1447    /// See more about the [fused multiply-add
1448    /// function](crate#fused-multiply-add).
1449    #[must_use = doc::must_use_op!()]
1450    #[track_caller]
1451    #[inline]
1452    pub const fn mul_add(self, a: Self, b: Self) -> Self {
1453        math::add::add(self.mul(a), b)
1454            .round_extra_precision()
1455            .check()
1456    }
1457
1458    /// Returns the given decimal number rounded to `digits` precision after the
1459    /// decimal point, using [RoundingMode] from it [Context].
1460    ///
1461    /// # Panics:
1462    #[doc = doc::decimal_operation_panics!("round operation (up-scale or down-scale)")]
1463    /// # Examples
1464    ///
1465    /// ```
1466    /// use fastnum::{*, decimal::{*, RoundingMode::*}};
1467    ///
1468    /// let n = dec256!(129.41675);
1469    ///
1470    /// // Default rounding mode is `HalfUp`
1471    /// assert_eq!(n.round(2),  dec256!(129.42));
1472    ///
1473    /// assert_eq!(n.with_rounding_mode(Up).round(2), dec256!(129.42));
1474    /// assert_eq!(n.with_rounding_mode(Down).round(-1), dec256!(120));
1475    /// assert_eq!(n.with_rounding_mode(HalfEven).round(4), dec256!(129.4168));
1476    /// ```
1477    /// See also:
1478    /// - More about [`round`](crate#rounding) decimals.
1479    /// - [RoundingMode].
1480    #[must_use = doc::must_use_op!()]
1481    #[track_caller]
1482    #[inline(always)]
1483    pub const fn round(self, digits: i16) -> Self {
1484        self.rescale(digits)
1485    }
1486
1487    #[doc = doc::trunc::trunc!(256)]
1488    #[must_use = doc::must_use_op!()]
1489    #[inline(always)]
1490    pub const fn trunc(self) -> Self {
1491        truncate::truncate(self, 0).check()
1492    }
1493
1494    #[doc = doc::trunc::trunc_with_scale!(256)]
1495    #[must_use = doc::must_use_op!()]
1496    #[inline(always)]
1497    pub const fn trunc_with_scale(self, scale: i16) -> Self {
1498        truncate::truncate(self, scale).check()
1499    }
1500
1501    /// Returns the largest integer less than or equal to a number.
1502    ///
1503    /// # Examples
1504    ///
1505    /// ```
1506    /// use fastnum::*;
1507    ///
1508    /// assert_eq!(dec256!(3.99).floor(), dec256!(3));
1509    /// assert_eq!(dec256!(3.0).floor(), dec256!(3));
1510    /// assert_eq!(dec256!(3.01).floor(), dec256!(3));
1511    /// assert_eq!(dec256!(3.5).floor(), dec256!(3));
1512    /// assert_eq!(dec256!(4.0).floor(), dec256!(4));
1513    ///
1514    /// assert_eq!(dec256!(-3.01).floor(), dec256!(-4));
1515    /// assert_eq!(dec256!(-3.1).floor(), dec256!(-4));
1516    /// assert_eq!(dec256!(-3.5).floor(), dec256!(-4));
1517    /// assert_eq!(dec256!(-4.0).floor(), dec256!(-4));
1518    /// ```
1519    #[must_use = doc::must_use_op!()]
1520    #[track_caller]
1521    #[inline]
1522    pub const fn floor(self) -> Self {
1523        round::floor(self)
1524    }
1525
1526    /// Finds the nearest integer greater than or equal to `x`.
1527    ///
1528    /// # Examples
1529    ///
1530    /// ```
1531    /// use fastnum::*;
1532    ///
1533    /// assert_eq!(dec256!(3.01).ceil(), dec256!(4));
1534    /// assert_eq!(dec256!(3.99).ceil(), dec256!(4));
1535    /// assert_eq!(dec256!(4.0).ceil(), dec256!(4));
1536    /// assert_eq!(dec256!(1.0001).ceil(), dec256!(2));
1537    /// assert_eq!(dec256!(1.00001).ceil(), dec256!(2));
1538    /// assert_eq!(dec256!(1.000001).ceil(), dec256!(2));
1539    /// assert_eq!(dec256!(1.00000000000001).ceil(), dec256!(2));
1540    ///
1541    /// assert_eq!(dec256!(-3.01).ceil(), dec256!(-3));
1542    /// assert_eq!(dec256!(-3.5).ceil(), dec256!(-3));
1543    /// assert_eq!(dec256!(-4.0).ceil(), dec256!(-4));
1544    /// ```
1545    #[must_use = doc::must_use_op!()]
1546    #[track_caller]
1547    #[inline]
1548    pub const fn ceil(self) -> Self {
1549        round::ceil(self)
1550    }
1551
1552    /// Returns the given decimal number _re-scaled_ to `digits` precision after
1553    /// the decimal point.
1554    ///
1555    /// # Panics:
1556    #[doc = doc::decimal_operation_panics!("rescale operation")]
1557    /// # Examples
1558    ///
1559    /// ```
1560    /// use fastnum::{*, decimal::*};
1561    ///
1562    /// assert_eq!(dec256!(2.17).rescale(3), dec256!(2.170));
1563    /// assert_eq!(dec256!(2.17).rescale(2), dec256!(2.17));
1564    /// assert_eq!(dec256!(2.17).rescale(1), dec256!(2.2));
1565    /// assert_eq!(dec256!(2.17).rescale(0), dec256!(2));
1566    /// assert_eq!(dec256!(2.17).rescale(-1), dec256!(0));
1567    ///
1568    /// let ctx = Context::default().without_traps();
1569    ///
1570    /// assert!(D256::INFINITY.with_ctx(ctx).rescale(2).is_nan());
1571    /// assert!(D256::NEG_INFINITY.with_ctx(ctx).rescale(2).is_nan());
1572    /// assert!(D256::NAN.with_ctx(ctx).rescale(1).is_nan());
1573    /// ```
1574    ///
1575    /// See also:
1576    /// - More about [`rescale`](crate#rescale) decimals.
1577    /// - [Self::quantize].
1578    #[must_use = doc::must_use_op!()]
1579    #[track_caller]
1580    #[inline(always)]
1581    pub const fn rescale(mut self, new_scale: i16) -> Self {
1582        scale::rescale(&mut self, new_scale);
1583        self.round_extra_precision().check()
1584    }
1585
1586    /// Returns a value equal to `self` (rounded), having the exponent of
1587    /// `other`.
1588    ///
1589    /// # Panics:
1590    #[doc = doc::decimal_operation_panics!("quantize operation")]
1591    /// # Examples
1592    ///
1593    /// ```
1594    /// use fastnum::{*, decimal::*};
1595    ///
1596    /// let ctx = Context::default().without_traps();
1597    ///
1598    /// assert_eq!(dec256!(2.17).quantize(dec256!(0.001)), dec256!(2.170));
1599    /// assert_eq!(dec256!(2.17).quantize(dec256!(0.01)), dec256!(2.17));
1600    /// assert_eq!(dec256!(2.17).quantize(dec256!(0.1)), dec256!(2.2));
1601    /// assert_eq!(dec256!(2.17).quantize(dec256!(1e+0)), dec256!(2));
1602    /// assert_eq!(dec256!(2.17).quantize(dec256!(1e+1)), dec256!(0));
1603    ///
1604    /// assert_eq!(D256::NEG_INFINITY.quantize(D256::INFINITY), D256::NEG_INFINITY);
1605    ///
1606    /// assert!(dec256!(2).with_ctx(ctx).quantize(D256::INFINITY).is_nan());
1607    ///
1608    /// assert_eq!(dec256!(-0.1).quantize(dec256!(1)), dec256!(-0));
1609    /// assert_eq!(dec256!(-0).quantize(dec256!(1e+5)), dec256!(-0E+5));
1610    ///
1611    /// assert!(dec128!(0.34028).with_ctx(ctx).quantize(dec128!(1e-32765)).is_nan());
1612    /// assert!(dec128!(-0.34028).with_ctx(ctx).quantize(dec128!(1e-32765)).is_nan());
1613    ///
1614    /// assert_eq!(dec256!(217).quantize(dec256!(1e-1)), dec256!(217.0));
1615    /// assert_eq!(dec256!(217).quantize(dec256!(1e+0)), dec256!(217));
1616    /// assert_eq!(dec256!(217).quantize(dec256!(1e+1)), dec256!(2.2E+2));
1617    /// assert_eq!(dec256!(217).quantize(dec256!(1e+2)), dec256!(2E+2));
1618    /// ```
1619    ///
1620    /// See also:
1621    /// - More about [`quantize`](crate#quantize) decimals.
1622    /// - [Self::rescale].
1623    #[must_use = doc::must_use_op!()]
1624    #[track_caller]
1625    #[inline]
1626    pub const fn quantize(self, other: Self) -> Self {
1627        scale::quantize(self, other).round_extra_precision().check()
1628    }
1629
1630    /// Returns:
1631    /// - `true` if no [Exceptional condition] [Signals] flag has been trapped
1632    ///   by [Context] trap-enabler, and
1633    /// - `false` otherwise.
1634    ///
1635    /// [Exceptional condition]: crate#signaling-flags-and-trap-enablers
1636    #[inline(always)]
1637    pub const fn is_ok(&self) -> bool {
1638        self.cb.trap_signals().is_empty()
1639    }
1640
1641    /// Returns:
1642    /// - `Some(Self)` if no [Exceptional condition] [Signals] flag has been
1643    ///   trapped by [Context] trap-enabler, and
1644    /// - `None` otherwise.
1645    ///
1646    /// [Exceptional condition]: crate#signaling-flags-and-trap-enablers
1647    #[inline]
1648    pub const fn ok(self) -> Option<Self> {
1649        if self.cb.trap_signals().is_empty() {
1650            Some(self)
1651        } else {
1652            None
1653        }
1654    }
1655
1656    /// Takes the reciprocal (inverse) of a number, `1/x`.
1657    #[doc = doc::decimal_inexact!("reciprocal")]
1658    /// # Panics:
1659    #[doc = doc::decimal_operation_panics!("reciprocal operation")]
1660    /// # Examples
1661    ///
1662    /// ```
1663    /// use fastnum::*;
1664    ///
1665    /// assert_eq!(dec256!(2).recip(), dec256!(0.5));
1666    /// ```
1667    #[must_use = doc::must_use_op!()]
1668    #[track_caller]
1669    #[inline]
1670    pub const fn recip(self) -> Self {
1671        math::recip::recip(self).round_extra_precision().check()
1672    }
1673
1674    /// Converts radians to degrees.
1675    ///
1676    /// # Panics:
1677    #[doc = doc::decimal_operation_panics!("conversion")]
1678    /// # Examples
1679    ///
1680    /// ```
1681    /// use fastnum::*;
1682    ///
1683    /// assert_eq!(D128::PI.to_degrees(), dec128!(180));
1684    /// assert_eq!(D128::TAU.to_degrees(), dec128!(360));
1685    /// ```
1686    #[must_use = doc::must_use_op!()]
1687    #[inline]
1688    pub const fn to_degrees(self) -> Self {
1689        math::mul::mul(math::div::div(self, Self::PI), Consts::C_180)
1690            .round_extra_precision()
1691            .check()
1692    }
1693
1694    /// Converts degrees to radians.
1695    ///
1696    /// # Panics:
1697    #[doc = doc::decimal_operation_panics!("conversion")]
1698    /// # Examples
1699    ///
1700    /// ```
1701    /// use fastnum::*;
1702    ///
1703    /// assert_eq!(dec128!(180).to_radians(), D128::PI);
1704    /// assert_eq!(dec128!(360).to_radians(), D128::TAU);
1705    /// ```
1706    #[must_use = doc::must_use_op!()]
1707    #[inline]
1708    pub const fn to_radians(self) -> Self {
1709        math::div::div(math::mul::mul(self, Self::PI), Consts::C_180)
1710            .round_extra_precision()
1711            .check()
1712    }
1713
1714    /// Create a string of this decimal in scientific notation.
1715    ///
1716    /// # Examples
1717    ///
1718    /// ```
1719    /// use fastnum::dec256;
1720    ///
1721    /// let n = dec256!(-12345678);
1722    /// assert_eq!(&n.to_scientific_notation(), "-1.2345678e7");
1723    /// ```
1724    #[must_use = doc::must_use_op!()]
1725    #[inline]
1726    pub fn to_scientific_notation(&self) -> String {
1727        let mut output = String::new();
1728        self.write_scientific_notation(&mut output)
1729            .expect("Could not write to string");
1730        output
1731    }
1732
1733    /// Create a string of this decimal in engineering notation.
1734    ///
1735    /// Engineering notation is scientific notation with the exponent
1736    /// coerced to a multiple of three
1737    ///
1738    /// # Examples
1739    ///
1740    /// ```
1741    /// use fastnum::dec256;
1742    ///
1743    /// let n = dec256!(-12345678);
1744    /// assert_eq!(&n.to_engineering_notation(), "-12.345678e6");
1745    /// ```
1746    #[must_use = doc::must_use_op!()]
1747    #[inline]
1748    pub fn to_engineering_notation(&self) -> String {
1749        let mut output = String::new();
1750        self.write_engineering_notation(&mut output)
1751            .expect("Could not write to string");
1752        output
1753    }
1754
1755    /// _Deprecated_, use [`resize`](Self::resize) instead.
1756    #[deprecated(since = "0.5.0")]
1757    #[must_use = doc::must_use_op!()]
1758    #[inline(always)]
1759    pub const fn transmute<const M: usize>(self) -> Decimal<M> {
1760        self.resize()
1761    }
1762
1763    #[doc = doc::resize::resize!(64)]
1764    #[must_use = doc::must_use_op!()]
1765    #[inline(always)]
1766    pub const fn resize<const M: usize>(self) -> Decimal<M> {
1767        resize::resize(self).round_extra_precision().check()
1768    }
1769
1770    /// Returns `true` if the decimal number is even.
1771    ///
1772    /// # Examples
1773    ///
1774    /// ```
1775    /// use fastnum::dec256;
1776    ///
1777    /// assert_eq!(dec256!(3).is_even(), false);
1778    /// assert_eq!(dec256!(4).is_even(), true);
1779    /// ```
1780    #[must_use = doc::must_use_op!()]
1781    #[inline]
1782    pub const fn is_even(&self) -> bool {
1783        math::utils::is_even(self)
1784    }
1785
1786    /// Returns `true` if the decimal number is odd.
1787    ///
1788    /// # Examples
1789    ///
1790    /// ```
1791    /// use fastnum::dec256;
1792    ///
1793    /// assert_eq!(dec256!(3).is_odd(), true);
1794    /// assert_eq!(dec256!(4).is_odd(), false);
1795    /// ```
1796    #[must_use = doc::must_use_op!()]
1797    #[inline]
1798    pub const fn is_odd(&self) -> bool {
1799        math::utils::is_odd(self)
1800    }
1801
1802    /// Returns `true` if the decimal number is integral.
1803    ///
1804    /// # Examples
1805    ///
1806    /// ```
1807    /// use fastnum::dec256;
1808    ///
1809    /// assert_eq!(dec256!(3.3).is_integral(), false);
1810    /// assert_eq!(dec256!(4).is_integral(), true);
1811    /// assert_eq!(dec256!(1.0).is_integral(), true);
1812    /// assert_eq!(dec256!(10.0).is_integral(), true);
1813    /// ```
1814    #[must_use = doc::must_use_op!()]
1815    #[inline]
1816    pub const fn is_integral(&self) -> bool {
1817        math::utils::is_integral(self)
1818    }
1819
1820    /// Computes _sin(self)_ (trigonometric sine of decimal number in radians).
1821    #[doc = doc::decimal_inexact!("trigonometric sine")]
1822    /// # Panics:
1823    #[doc = doc::decimal_operation_panics!("trigonometric sine operation")]
1824    /// # Examples
1825    ///
1826    /// Basic usage:
1827    ///
1828    /// ```
1829    /// use fastnum::*;
1830    ///
1831    /// assert_eq!(D128::FRAC_PI_2.sin(), dec128!(1));
1832    /// ```
1833    ///
1834    /// See more about the [trigonometric
1835    /// functions](crate#trigonometric-functions).
1836    #[must_use = doc::must_use_op!()]
1837    #[inline]
1838    pub const fn sin(self) -> Self {
1839        math::sin::sin(self).round_extra_precision().check()
1840    }
1841
1842    /// Computes _cos(self)_ (trigonometric cosine of decimal number in
1843    /// radians).
1844    #[doc = doc::decimal_inexact!("trigonometric cosine")]
1845    /// # Panics:
1846    #[doc = doc::decimal_operation_panics!("trigonometric cosine operation")]
1847    /// # Examples
1848    ///
1849    /// Basic usage:
1850    ///
1851    /// ```
1852    /// use fastnum::*;
1853    ///
1854    /// assert_eq!(D128::TAU.cos(), dec128!(1));
1855    /// ```
1856    ///
1857    /// See more about the [trigonometric
1858    /// functions](crate#trigonometric-functions).
1859    #[must_use = doc::must_use_op!()]
1860    #[inline]
1861    pub const fn cos(self) -> Self {
1862        math::cos::cos(self).round_extra_precision().check()
1863    }
1864
1865    /// Computes _tan(self)_ (trigonometric tangent of decimal number in
1866    /// radians).
1867    #[doc = doc::decimal_inexact!("trigonometric tangent")]
1868    /// # Panics:
1869    #[doc = doc::decimal_operation_panics!("trigonometric tangent operation")]
1870    /// # Examples
1871    ///
1872    /// Basic usage:
1873    ///
1874    /// ```
1875    /// use fastnum::*;
1876    ///
1877    /// assert_eq!(D128::FRAC_PI_4.tan(), dec128!(1));
1878    /// ```
1879    ///
1880    /// See more about the [trigonometric
1881    /// functions](crate#trigonometric-functions).
1882    #[must_use = doc::must_use_op!()]
1883    #[inline]
1884    pub const fn tan(self) -> Self {
1885        math::tan::tan(self).round_extra_precision().check()
1886    }
1887
1888    /// Computes _arcsin(self)_ (trigonometric arcsine of decimal number).
1889    ///
1890    /// Return value is in radians in the range [-π/2, π/2] or `NaN`
1891    /// if the number is outside the range [-1, 1].
1892    #[doc = doc::decimal_inexact!("trigonometric arcsine")]
1893    /// # Panics:
1894    #[doc = doc::decimal_operation_panics!("trigonometric arcsine operation")]
1895    /// # Examples
1896    ///
1897    /// Basic usage:
1898    ///
1899    /// ```
1900    /// use fastnum::*;
1901    ///
1902    /// assert_eq!(D128::FRAC_PI_2.sin().asin(), D128::FRAC_PI_2);
1903    /// ```
1904    ///
1905    /// See more about the [trigonometric
1906    /// functions](crate#trigonometric-functions).
1907    #[must_use = doc::must_use_op!()]
1908    #[inline]
1909    pub const fn asin(self) -> Self {
1910        math::asin::asin(self).round_extra_precision().check()
1911    }
1912
1913    /// Computes _arccos(self)_ (trigonometric arccosine of decimal number).
1914    ///
1915    /// Return value is in radians in the range [0, π] or `NaN`
1916    /// if the number is outside the range [-1, 1].
1917    #[doc = doc::decimal_inexact!("trigonometric arccosine")]
1918    /// # Panics:
1919    #[doc = doc::decimal_operation_panics!("trigonometric arccosine operation")]
1920    /// # Examples
1921    ///
1922    /// Basic usage:
1923    ///
1924    /// ```
1925    /// use fastnum::*;
1926    ///
1927    /// assert_eq!(dec256!(1).acos(), dec256!(0));
1928    /// ```
1929    ///
1930    /// See more about the [trigonometric
1931    /// functions](crate#trigonometric-functions).
1932    #[must_use = doc::must_use_op!()]
1933    #[inline]
1934    pub const fn acos(self) -> Self {
1935        math::acos::acos(self).round_extra_precision().check()
1936    }
1937
1938    /// Computes _arctan(self)_ (trigonometric arctangent of decimal number).
1939    ///
1940    /// Return value is in radians in the range [-π/2, π/2].
1941    #[doc = doc::decimal_inexact!("trigonometric arctangent")]
1942    /// # Panics:
1943    #[doc = doc::decimal_operation_panics!("trigonometric arctangent operation")]
1944    /// # Examples
1945    ///
1946    /// Basic usage:
1947    ///
1948    /// ```
1949    /// use fastnum::*;
1950    ///
1951    /// assert_eq!(D128::ZERO.atan(), D128::ZERO);
1952    /// assert_eq!(D128::ONE.atan(), D128::FRAC_PI_4);
1953    /// assert_eq!(D128::ONE.neg().atan(), D128::FRAC_PI_4.neg());
1954    /// ```
1955    ///
1956    /// See more about the [trigonometric
1957    /// functions](crate#trigonometric-functions).
1958    #[must_use = doc::must_use_op!()]
1959    #[inline]
1960    pub const fn atan(self) -> Self {
1961        math::atan::atan(self).round_extra_precision().check()
1962    }
1963
1964    /// Computes the [_four quadrant_ arctangent](https://en.wikipedia.org/wiki/Atan2)
1965    /// of `self` (`y`) and `other` (`x`).
1966    ///
1967    /// * `x = 0`, `y = 0`: `0`
1968    /// * `x >= 0`: `arctan(y/x)` -> `[-π/2, π/2]`
1969    /// * `y >= 0`: `arctan(y/x) + π` -> `(pi/2, π]`
1970    /// * `y < 0`: `arctan(y/x) - π` -> `(-π, -π/2)`
1971    #[doc = doc::decimal_inexact!("trigonometric 2-argument arctangent")]
1972    /// # Panics:
1973    #[doc = doc::decimal_operation_panics!("trigonometric 2-argument arctangent operation")]
1974    /// # Examples
1975    ///
1976    /// Basic usage:
1977    ///
1978    /// ```
1979    /// use fastnum::*;
1980    ///
1981    /// assert_eq!(dec128!(-3.0).atan2(dec128!(3.0)), D128::FRAC_PI_4.neg());
1982    /// assert_eq!(dec128!(3.0).atan2(dec128!(-3.0)), D128::FRAC_PI_4 * D128::THREE);
1983    /// ```
1984    ///
1985    /// See more about the [trigonometric
1986    /// functions](crate#trigonometric-functions).
1987    #[must_use = doc::must_use_op!()]
1988    #[inline]
1989    pub const fn atan2(self, other: Self) -> Self {
1990        math::atan2::atan2(self, other)
1991            .round_extra_precision()
1992            .check()
1993    }
1994
1995    /// Simultaneously computes the sine and cosine of the number, `x`.
1996    /// Returns `(sin(x), cos(x))`.
1997    #[doc = doc::decimal_inexact!("trigonometric sine and cosine function")]
1998    /// # Panics:
1999    #[doc = doc::decimal_operation_panics!("trigonometric sine and cosine computation")]
2000    /// # Examples
2001    ///
2002    /// Basic usage:
2003    ///
2004    /// ```
2005    /// use fastnum::*;
2006    ///
2007    /// assert_eq!(D128::FRAC_PI_2.sin_cos(), (dec128!(1), dec128!(0)));
2008    /// ```
2009    ///
2010    /// See more about the [trigonometric
2011    /// functions](crate#trigonometric-functions).
2012    #[must_use = doc::must_use_op!()]
2013    #[inline]
2014    pub const fn sin_cos(self) -> (Self, Self) {
2015        let (sin, cos) = math::sin_cos::sin_cos(self);
2016        (
2017            sin.round_extra_precision().check(),
2018            cos.round_extra_precision().check(),
2019        )
2020    }
2021
2022    /// Computes _sinh(self)_ (hyperbolic sine of decimal number).
2023    #[doc = doc::decimal_inexact!("hyperbolic sine")]
2024    /// # Panics:
2025    #[doc = doc::decimal_operation_panics!("hyperbolic sine operation")]
2026    /// # Examples
2027    ///
2028    /// Basic usage:
2029    ///
2030    /// ```
2031    /// use fastnum::*;
2032    ///
2033    /// assert_eq!(dec128!(1).sinh(), (D128::E * D128::E - dec128!(1.0)) / (dec128!(2.0) * D128::E));
2034    /// ```
2035    ///
2036    /// See more about the [trigonometric
2037    /// functions](crate#trigonometric-functions).
2038    #[must_use = doc::must_use_op!()]
2039    #[inline]
2040    pub const fn sinh(self) -> Self {
2041        math::sinh::sinh(self).round_extra_precision().check()
2042    }
2043
2044    /// Computes _cosh(self)_ (hyperbolic cosine of decimal number).
2045    #[doc = doc::decimal_inexact!("hyperbolic cosine")]
2046    /// # Panics:
2047    #[doc = doc::decimal_operation_panics!("hyperbolic cosine operation")]
2048    /// # Examples
2049    ///
2050    /// Basic usage:
2051    ///
2052    /// ```
2053    /// use fastnum::*;
2054    ///
2055    /// assert_eq!(dec256!(1).cosh(), (D256::E * D256::E + dec256!(1.0)) / (dec256!(2.0) * D256::E));
2056    /// ```
2057    ///
2058    /// See more about the [trigonometric
2059    /// functions](crate#trigonometric-functions).
2060    #[must_use = doc::must_use_op!()]
2061    #[inline]
2062    pub const fn cosh(self) -> Self {
2063        math::cosh::cosh(self).round_extra_precision().check()
2064    }
2065
2066    /// Computes _tanh(self)_ (hyperbolic tangent of decimal number).
2067    #[doc = doc::decimal_inexact!("hyperbolic tangent")]
2068    /// # Panics:
2069    #[doc = doc::decimal_operation_panics!("hyperbolic tangent operation")]
2070    /// # Examples
2071    ///
2072    /// Basic usage:
2073    ///
2074    /// ```
2075    /// use fastnum::*;
2076    ///
2077    /// let e2 = D128::E * D128::E;
2078    /// assert_eq!(dec128!(1).tanh(), (e2 - dec128!(1.0)) / (e2 + dec128!(1.0)));
2079    /// ```
2080    ///
2081    /// See more about the [trigonometric
2082    /// functions](crate#trigonometric-functions).
2083    #[must_use = doc::must_use_op!()]
2084    #[inline]
2085    pub const fn tanh(self) -> Self {
2086        math::tanh::tanh(self).round_extra_precision().check()
2087    }
2088
2089    /// Computes _arsinh(self)_ (inverse hyperbolic sine of decimal number).
2090    #[doc = doc::decimal_inexact!("inverse hyperbolic sine")]
2091    /// # Panics:
2092    #[doc = doc::decimal_operation_panics!("inverse hyperbolic sine operation")]
2093    /// # Examples
2094    ///
2095    /// Basic usage:
2096    ///
2097    /// ```
2098    /// use fastnum::*;
2099    ///
2100    /// assert_eq!(dec128!(1).sinh().asinh(), dec128!(1));
2101    /// ```
2102    ///
2103    /// See more about the [trigonometric
2104    /// functions](crate#trigonometric-functions).
2105    #[must_use = doc::must_use_op!()]
2106    #[inline]
2107    pub const fn asinh(self) -> Self {
2108        math::asinh::asinh(self).round_extra_precision().check()
2109    }
2110
2111    /// Computes _arcosh(self)_ (inverse hyperbolic cosine of decimal number).
2112    #[doc = doc::decimal_inexact!("inverse hyperbolic cosine")]
2113    /// # Panics:
2114    #[doc = doc::decimal_operation_panics!("inverse hyperbolic cosine operation")]
2115    /// # Examples
2116    ///
2117    /// Basic usage:
2118    ///
2119    /// ```
2120    /// use fastnum::*;
2121    ///
2122    /// assert_eq!(dec128!(1).cosh().acosh(), dec128!(1));
2123    /// ```
2124    ///
2125    /// See more about the [trigonometric
2126    /// functions](crate#trigonometric-functions).
2127    #[must_use = doc::must_use_op!()]
2128    #[inline]
2129    pub const fn acosh(self) -> Self {
2130        math::acosh::acosh(self).round_extra_precision().check()
2131    }
2132
2133    /// Computes _artanh(self)_ (inverse hyperbolic tangent of decimal number).
2134    #[doc = doc::decimal_inexact!("inverse hyperbolic tangent")]
2135    /// # Panics:
2136    #[doc = doc::decimal_operation_panics!("inverse hyperbolic tangent operation")]
2137    /// # Examples
2138    ///
2139    /// Basic usage:
2140    ///
2141    /// ```
2142    /// use fastnum::*;
2143    ///
2144    /// assert_eq!(D256::ZERO.tanh().atanh(), D256::ZERO);
2145    /// ```
2146    ///
2147    /// See more about the [trigonometric
2148    /// functions](crate#trigonometric-functions).
2149    #[must_use = doc::must_use_op!()]
2150    #[inline]
2151    pub const fn atanh(self) -> Self {
2152        math::atanh::atanh(self).round_extra_precision().check()
2153    }
2154
2155    /// Converts from [UnsignedDecimal] to a signed [Decimal] number.
2156    ///
2157    /// # Examples
2158    ///
2159    /// ```
2160    /// use fastnum::*;
2161    ///
2162    /// let d = udec256!(1.2345);
2163    ///
2164    /// assert_eq!(D256::from_unsigned(d), dec256!(1.2345));
2165    /// ```
2166    #[must_use = doc::must_use_op!()]
2167    #[inline]
2168    pub const fn from_unsigned(ud: UnsignedDecimal<N>) -> Self {
2169        ud.to_signed()
2170    }
2171
2172    /// Try converts from [Decimal] to [UnsignedDecimal].
2173    ///
2174    /// # Examples
2175    ///
2176    /// ```
2177    /// use fastnum::*;
2178    ///
2179    /// assert_eq!(dec256!(1.2345).try_to_unsigned(), Ok(udec256!(1.2345)));
2180    /// assert!(dec256!(-1.2345).try_to_unsigned().is_err());
2181    /// ```
2182    #[inline]
2183    pub const fn try_to_unsigned(self) -> Result<UnsignedDecimal<N>, DecimalError> {
2184        UnsignedDecimal::try_from_signed(self)
2185    }
2186}
2187
2188#[doc(hidden)]
2189impl<const N: usize> Decimal<N> {
2190    pub(crate) const SIGNALING_NAN: Self = Self::new(UInt::ZERO, ControlBlock::SIGNALING_NAN);
2191
2192    const TYPE_NAME: &'static str = decimal::utils::fmt::type_name!("D");
2193
2194    #[inline(always)]
2195    pub(crate) const fn new(digits: UInt<N>, cb: ControlBlock) -> Self {
2196        Self { digits, cb }
2197    }
2198
2199    #[inline(always)]
2200    pub(crate) const fn decimal_power(&self) -> i32 {
2201        self.digits_count() as i32 - self.cb.get_scale() as i32
2202    }
2203
2204    #[inline(always)]
2205    pub(crate) fn control_block(&self) -> ControlBlock {
2206        self.cb
2207    }
2208
2209    #[inline(always)]
2210    pub(crate) const fn signals(&self) -> Signals {
2211        self.cb.get_signals()
2212    }
2213
2214    #[inline(always)]
2215    pub(crate) const fn context(&self) -> Context {
2216        self.cb.get_context()
2217    }
2218
2219    #[inline(always)]
2220    pub(crate) const fn raise_signals(mut self, signals: Signals) -> Self {
2221        self.cb.raise_signals(signals);
2222        self
2223    }
2224
2225    #[allow(dead_code)]
2226    #[inline(always)]
2227    pub(crate) const fn quiet_signals(mut self, signals: Signals) -> Self {
2228        self.cb.quiet_signals(signals);
2229        self
2230    }
2231
2232    #[inline(always)]
2233    pub(crate) const fn compound(mut self, other: &Self) -> Self {
2234        self.cb.compound(&other.cb);
2235        self
2236    }
2237
2238    #[inline(always)]
2239    pub(crate) const fn signaling_nan(mut self) -> Self {
2240        self.cb.signaling_nan();
2241        self
2242    }
2243
2244    #[inline(always)]
2245    pub(crate) const fn op_invalid(mut self) -> Self {
2246        self.cb.raise_signals(Signals::OP_INVALID);
2247        self
2248    }
2249
2250    #[inline(always)]
2251    pub(crate) const fn op_overflow(mut self) -> Self {
2252        self.cb.raise_signals(Signals::OP_OVERFLOW);
2253        self
2254    }
2255
2256    #[inline(always)]
2257    pub(crate) const fn set_sign(mut self, sign: Sign) -> Self {
2258        self.cb.set_sign(sign);
2259        self
2260    }
2261
2262    #[inline(always)]
2263    pub(crate) const fn set_ctx(mut self, ctx: Context) -> Self {
2264        self.cb.set_context(ctx);
2265        self
2266    }
2267
2268    #[inline(always)]
2269    pub(crate) const fn set_rounding_mode(mut self, rm: RoundingMode) -> Self {
2270        self.cb.set_rounding_mode(rm);
2271        self
2272    }
2273
2274    #[inline(always)]
2275    pub(crate) const fn check(mut self) -> Self {
2276        let trapped = self.cb.trap_signals();
2277
2278        if !trapped.is_empty() {
2279            DecimalError::from_signals(trapped).panic();
2280            self.cb.signaling_nan();
2281        }
2282
2283        self
2284    }
2285
2286    #[inline(always)]
2287    pub(crate) const fn ok_or_err(self) -> Result<Self, DecimalError> {
2288        let trapped = self.cb.trap_signals();
2289
2290        if trapped.is_empty() {
2291            Ok(self)
2292        } else {
2293            Err(DecimalError::from_signals(trapped))
2294        }
2295    }
2296
2297    #[inline(always)]
2298    pub(crate) const fn round_extra_precision(mut self) -> Self {
2299        round(&mut self);
2300        self
2301    }
2302
2303    #[inline(always)]
2304    pub(crate) const fn without_extra_digits(mut self) -> Self {
2305        self.cb.reset_extra_precision();
2306        self
2307    }
2308
2309    #[inline(always)]
2310    pub(crate) const fn has_extra_precision(&self) -> bool {
2311        self.cb.has_extra_precision()
2312    }
2313
2314    #[inline]
2315    pub(crate) const fn type_name() -> &'static str {
2316        Self::TYPE_NAME
2317    }
2318
2319    /// Write unsigned decimal in scientific notation to writer `w`.
2320    pub(crate) fn write_scientific_notation<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
2321        if self.is_nan() {
2322            return w.write_str("NaN");
2323        }
2324
2325        if self.is_sign_negative() {
2326            w.write_str("-")?;
2327        }
2328
2329        if self.is_infinite() {
2330            return w.write_str("Inf");
2331        }
2332
2333        if self.is_zero() {
2334            return w.write_str("0e0");
2335        }
2336
2337        let digits = self.digits.to_str_radix(10);
2338        let scale = self.cb.get_scale();
2339        format::write_scientific_notation(digits, scale, w)
2340    }
2341
2342    /// Write unsigned decimal in engineering notation to writer `w`.
2343    pub(crate) fn write_engineering_notation<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
2344        if self.is_nan() {
2345            return w.write_str("NaN");
2346        }
2347
2348        if self.is_sign_negative() {
2349            w.write_str("-")?;
2350        }
2351
2352        if self.is_infinite() {
2353            return w.write_str("Inf");
2354        }
2355
2356        if self.is_zero() {
2357            return w.write_str("0e0");
2358        }
2359
2360        let digits = self.digits.to_str_radix(10);
2361        let scale = self.cb.get_scale();
2362        format::write_engineering_notation(digits, scale, w)
2363    }
2364
2365    #[allow(unsafe_code)]
2366    #[inline(always)]
2367    pub(crate) const unsafe fn _transmute<const M: usize>(self) -> Decimal<M> {
2368        Decimal::new(self.digits._transmute(), self.cb)
2369    }
2370}