Skip to main content

zu_common/
decimal.rs

1//! Exact decimal numbers, GV17.
2//!
3//! A decimal is an integer and a count of digits to move the point by,
4//! and that pair is the whole of it. `1.20` is a hundred and twenty
5//! hundredths, `1.2` is twelve tenths, and the two are the same number
6//! written with different care about how precisely it is known. Both
7//! facts matter here: they compare equal, and each prints back the way
8//! it was written.
9//!
10//! The reason for a type of its own rather than binary floating point
11//! is that a tenth is not a binary fraction. Adding `0.1` to `0.2` in
12//! binary64 gives a number that is not `0.3`, and no amount of care at
13//! the edges fixes it, because the value the machine holds was never
14//! three tenths. A ledger, a price and a tax rate are all counted in
15//! exact units of a tenth or a hundredth, so they are counted here as
16//! integers of those units and the scale says which unit.
17//!
18//! The unscaled integer is an `i128`, which holds thirty eight digits.
19//! That is the largest precision `DECIMAL(p, s)` may be declared with,
20//! so every declarable decimal fits one and the carrier never has to
21//! refuse a value the type admits.
22
23use std::cmp::Ordering;
24use std::fmt;
25
26/// The most digits a decimal may have, which is what an `i128` holds
27/// with room to spare for the sign.
28pub const MAX_DIGITS: u16 = 38;
29
30/// An exact decimal: `unscaled` units, each one ten to the minus
31/// `scale`.
32///
33/// The scale rides on the value rather than only on the declared type,
34/// because a decimal exists outside any column. `CAST('1.20' AS
35/// DECIMAL(5,2))` in a `RETURN` has no column to ask, and it still has
36/// to print two places.
37#[derive(Debug, Clone, Copy)]
38pub struct Decimal {
39    unscaled: i128,
40    scale: u16,
41}
42
43/// Which way a digit that will not fit is allowed to go.
44#[derive(Debug, Clone, Copy)]
45enum Round {
46    /// Half away from zero, which is the rule everywhere else in this
47    /// file and the one `ROUND` is expected to follow.
48    Half,
49    /// Toward positive infinity, for `CEIL`.
50    Up,
51    /// Toward negative infinity, for `FLOOR`.
52    Down,
53}
54
55impl Decimal {
56    /// A decimal of `unscaled` units of ten to the minus `scale`.
57    ///
58    /// Nothing is normalised. The caller wrote a scale and it is kept,
59    /// so a value cast to `DECIMAL(5,2)` prints two places even when
60    /// the second one is a nought.
61    pub fn new(unscaled: i128, scale: u16) -> Decimal {
62        Decimal { unscaled, scale }
63    }
64
65    /// The integer this is counted in units of.
66    pub fn unscaled(&self) -> i128 {
67        self.unscaled
68    }
69
70    /// How many of the digits are after the point.
71    pub fn scale(&self) -> u16 {
72        self.scale
73    }
74
75    /// Whether this is exactly zero, which the sign of the unscaled
76    /// integer does not answer on its own since zero has none.
77    pub fn is_zero(&self) -> bool {
78        self.unscaled == 0
79    }
80
81    /// How many digits the unscaled integer is written with, which is
82    /// the precision a value needs rather than the one it was declared
83    /// with. Zero is one digit.
84    pub fn digits(&self) -> u16 {
85        let mut left = self.unscaled.unsigned_abs();
86        let mut digits = 1;
87        while left >= 10 {
88            left /= 10;
89            digits += 1;
90        }
91        digits
92    }
93
94    /// This number written at `scale` instead, or `None` when the
95    /// change would not be exact or would not fit.
96    ///
97    /// Going to a larger scale multiplies and can overflow; going to a
98    /// smaller one divides and can drop a digit that is not a nought.
99    /// Both are refused rather than rounded, because the caller that
100    /// wants rounding says so and the caller that does not is asking
101    /// whether this number is one of that type at all.
102    pub fn rescale(&self, scale: u16) -> Option<Decimal> {
103        match scale.cmp(&self.scale) {
104            Ordering::Equal => Some(*self),
105            Ordering::Greater => {
106                let by = 10i128.checked_pow(u32::from(scale - self.scale))?;
107                Some(Decimal {
108                    unscaled: self.unscaled.checked_mul(by)?,
109                    scale,
110                })
111            }
112            Ordering::Less => {
113                let by = 10i128.checked_pow(u32::from(self.scale - scale))?;
114                match self.unscaled % by {
115                    0 => Some(Decimal {
116                        unscaled: self.unscaled / by,
117                        scale,
118                    }),
119                    _ => None,
120                }
121            }
122        }
123    }
124
125    /// This number without its sign, at the scale it was written with.
126    ///
127    /// `None` only for the one number an `i128` cannot negate.
128    pub fn abs(&self) -> Option<Decimal> {
129        Some(Decimal {
130            unscaled: self.unscaled.checked_abs()?,
131            scale: self.scale,
132        })
133    }
134
135    /// One, nought or minus one, after the sign of this number.
136    pub fn signum(&self) -> i64 {
137        self.unscaled.signum() as i64
138    }
139
140    /// This number rounded to `digits` places after the point, half
141    /// away from zero, which is what `ROUND` means over exact numbers.
142    ///
143    /// `digits` may be negative, which rounds to a place left of the
144    /// point: a hundred and fifty at minus two digits is two hundred.
145    /// The answer's scale is `digits` where that is a scale, and nought
146    /// where it is not, because a number rounded to hundreds has no
147    /// digits after the point to keep.
148    pub fn round(&self, digits: i64) -> Option<Decimal> {
149        self.quantize(digits, Round::Half)
150    }
151
152    /// This number taken up to the next `digits` place, toward positive
153    /// infinity, which is what `CEIL` means: `-1.5` ceils to `-1`.
154    pub fn ceil(&self, digits: i64) -> Option<Decimal> {
155        self.quantize(digits, Round::Up)
156    }
157
158    /// This number taken down to the previous `digits` place, toward
159    /// negative infinity: `-1.5` floors to `-2`.
160    pub fn floor(&self, digits: i64) -> Option<Decimal> {
161        self.quantize(digits, Round::Down)
162    }
163
164    /// The shared body of the three: the number written at scale
165    /// `digits` under `mode`, then brought back to a scale that exists,
166    /// which is `digits` itself where it is not negative and nought
167    /// where it is.
168    fn quantize(&self, digits: i64, mode: Round) -> Option<Decimal> {
169        let scale = u16::try_from(digits.max(0)).ok()?.min(MAX_DIGITS);
170        let drop = i64::from(self.scale) - digits;
171        if drop <= 0 {
172            return self.rescale(scale);
173        }
174        let by = 10i128.checked_pow(u32::try_from(drop).ok()?)?;
175        let (whole, rest) = (self.unscaled / by, self.unscaled % by);
176        let carried = match mode {
177            Round::Half if rest.checked_mul(2)?.abs() >= by => match self.unscaled.is_negative() {
178                true => whole.checked_sub(1)?,
179                false => whole.checked_add(1)?,
180            },
181            Round::Up if rest > 0 => whole.checked_add(1)?,
182            Round::Down if rest < 0 => whole.checked_sub(1)?,
183            _ => whole,
184        };
185        // Where the rounding went left of the point, the noughts it
186        // stood on go back: two hundreds is two hundred.
187        let back = 10i128.checked_pow(u32::try_from(i64::from(scale) - digits).ok()?)?;
188        Some(Decimal {
189            unscaled: carried.checked_mul(back)?,
190            scale,
191        })
192    }
193
194    /// The whole part of this number, with the digits past the point
195    /// dropped rather than rounded, so `1.9` is 1 and `-1.9` is -1.
196    ///
197    /// Truncation toward zero and not rounding, because that is what
198    /// the standard's cast to an exact integer does and the caller that
199    /// wants the nearest integer asks for it.
200    pub fn truncate(&self) -> Option<i128> {
201        let by = 10i128.checked_pow(u32::from(self.scale))?;
202        Some(self.unscaled / by)
203    }
204
205    /// This number as binary floating point, which is a narrowing and
206    /// is why it is spelled out rather than done wherever a float is
207    /// wanted.
208    ///
209    /// Every decimal has a nearest binary64 and most have no exact one,
210    /// so this is the edge where exactness ends. Callers reach it when
211    /// a decimal meets a float in arithmetic, where the answer is
212    /// inexact whatever is done, and when a function is defined on
213    /// binary floating point and on nothing else.
214    pub fn to_f64(&self) -> f64 {
215        self.unscaled as f64 / 10f64.powi(i32::from(self.scale))
216    }
217
218    /// The text read as a decimal at `scale`, rounded half away from
219    /// zero past the scale. `None` is text that is not a number, or a
220    /// number too large for the carrier.
221    ///
222    /// Half away from zero is what a person writing money means by
223    /// rounding, and it is what the standard's `CAST` to an exact
224    /// numeric permits an implementation to choose. An exponent is
225    /// accepted because `1E3` is a number a query may write, and it is
226    /// applied to the scale rather than to a float, so nothing goes
227    /// through binary on the way.
228    pub fn parse(text: &str, scale: u16) -> Option<Decimal> {
229        let text = text.trim();
230        let (negative, rest) = match text.strip_prefix('-') {
231            Some(rest) => (true, rest),
232            None => (false, text.strip_prefix('+').unwrap_or(text)),
233        };
234        let (mantissa, exponent) = match rest.split_once(['e', 'E']) {
235            Some((m, e)) => (m, e.parse::<i32>().ok()?),
236            None => (rest, 0),
237        };
238        let (whole, fraction) = match mantissa.split_once('.') {
239            Some((w, f)) => (w, f),
240            None => (mantissa, ""),
241        };
242        if whole.is_empty() && fraction.is_empty() {
243            return None;
244        }
245        if !whole
246            .bytes()
247            .chain(fraction.bytes())
248            .all(|b| b.is_ascii_digit())
249        {
250            return None;
251        }
252        // The digits are read as one integer and the point is then a
253        // number, which is the scale the text was written at, less
254        // whatever the exponent moved it by.
255        let mut digits: i128 = 0;
256        for byte in whole.bytes().chain(fraction.bytes()) {
257            digits = digits
258                .checked_mul(10)?
259                .checked_add(i128::from(byte - b'0'))?;
260        }
261        let written = i64::try_from(fraction.len())
262            .ok()?
263            .checked_sub(i64::from(exponent))?;
264        let unscaled = shift(digits, written, i64::from(scale))?;
265        Some(Decimal {
266            unscaled: match negative {
267                true => -unscaled,
268                false => unscaled,
269            },
270            scale,
271        })
272    }
273
274    /// The sum of two decimals, at the larger of the two scales, or
275    /// `None` on overflow.
276    ///
277    /// The wider scale is the exact one: a hundredth plus a tenth is a
278    /// number of hundredths, and answering in tenths would have to
279    /// throw a digit away.
280    pub fn add(&self, other: &Decimal) -> Option<Decimal> {
281        let (a, b) = align(self, other)?;
282        Some(Decimal {
283            unscaled: a.unscaled.checked_add(b.unscaled)?,
284            scale: a.scale,
285        })
286    }
287
288    /// The difference of two decimals, at the larger of the two scales.
289    pub fn sub(&self, other: &Decimal) -> Option<Decimal> {
290        let (a, b) = align(self, other)?;
291        Some(Decimal {
292            unscaled: a.unscaled.checked_sub(b.unscaled)?,
293            scale: a.scale,
294        })
295    }
296
297    /// The product of two decimals, whose scale is the sum of the two
298    /// scales, since that is what multiplying the units does.
299    pub fn mul(&self, other: &Decimal) -> Option<Decimal> {
300        let scale = self.scale.checked_add(other.scale)?;
301        if scale > MAX_DIGITS {
302            return None;
303        }
304        Some(Decimal {
305            unscaled: self.unscaled.checked_mul(other.unscaled)?,
306            scale,
307        })
308    }
309
310    /// The quotient of two decimals, or `None` for a division by zero
311    /// or an overflow.
312    ///
313    /// A quotient is the one operation exact arithmetic cannot always
314    /// answer exactly: a third has no decimal spelling at any scale. So
315    /// the answer is carried to a scale that keeps what the operands
316    /// knew and no further, and the last digit is rounded half away
317    /// from zero. The scale chosen is the larger operand scale plus six
318    /// guard digits, capped at the carrier, which is enough that money
319    /// divided by a count still says what a person would write.
320    pub fn div(&self, other: &Decimal) -> Option<Decimal> {
321        if other.unscaled == 0 {
322            return None;
323        }
324        let scale = self
325            .scale
326            .max(other.scale)
327            .saturating_add(6)
328            .min(MAX_DIGITS);
329        // Scale the numerator up by the answer's scale and by the
330        // divisor's own, since dividing by a number of hundredths
331        // multiplies by a hundred.
332        let up = i64::from(scale) + i64::from(other.scale) - i64::from(self.scale);
333        let numerator = shift(i128::try_from(self.unscaled.unsigned_abs()).ok()?, 0, up)?;
334        let divisor = i128::try_from(other.unscaled.unsigned_abs()).ok()?;
335        let quotient = numerator / divisor;
336        // Half away from zero: the remainder doubled reaching the
337        // divisor is a half or more.
338        let unscaled = match (numerator % divisor).checked_mul(2) {
339            Some(twice) if twice >= divisor => quotient.checked_add(1)?,
340            _ => quotient,
341        };
342        Some(Decimal {
343            unscaled: match self.unscaled.is_negative() != other.unscaled.is_negative() {
344                true => -unscaled,
345                false => unscaled,
346            },
347            scale,
348        })
349    }
350
351    /// The remainder of a division, at the larger of the two scales,
352    /// with the sign of the left operand as every other remainder in
353    /// this engine has.
354    pub fn rem(&self, other: &Decimal) -> Option<Decimal> {
355        let (a, b) = align(self, other)?;
356        if b.unscaled == 0 {
357            return None;
358        }
359        Some(Decimal {
360            unscaled: a.unscaled.checked_rem(b.unscaled)?,
361            scale: a.scale,
362        })
363    }
364
365    /// This number with its sign turned around.
366    pub fn negate(&self) -> Option<Decimal> {
367        Some(Decimal {
368            unscaled: self.unscaled.checked_neg()?,
369            scale: self.scale,
370        })
371    }
372}
373
374/// `digits`, written at scale `from`, read at scale `to`, rounding half
375/// away from zero where that loses a digit. `None` on overflow.
376fn shift<T>(digits: T, from: i64, to: i64) -> Option<i128>
377where
378    i128: TryFrom<T>,
379{
380    let digits = i128::try_from(digits).ok()?;
381    match to.checked_sub(from)? {
382        0 => Some(digits),
383        by if by > 0 => digits.checked_mul(10i128.checked_pow(u32::try_from(by).ok()?)?),
384        by => {
385            let down = 10i128.checked_pow(u32::try_from(-by).ok()?)?;
386            let whole = digits / down;
387            match (digits % down).checked_mul(2) {
388                Some(twice) if twice.abs() >= down => match digits.is_negative() {
389                    true => whole.checked_sub(1),
390                    false => whole.checked_add(1),
391                },
392                _ => Some(whole),
393            }
394        }
395    }
396}
397
398/// The two numbers written at one scale, which is the larger of theirs,
399/// so that the pair can be added, subtracted or compared as integers.
400fn align(a: &Decimal, b: &Decimal) -> Option<(Decimal, Decimal)> {
401    let scale = a.scale.max(b.scale);
402    Some((a.rescale(scale)?, b.rescale(scale)?))
403}
404
405/// Two decimals are equal when they are the same number, whatever scale
406/// each was written at, so `1.20` equals `1.2`.
407///
408/// The scale is how precisely a number is known and not part of which
409/// number it is. A query grouping prices would otherwise put `1.5` and
410/// `1.50` in two groups, which is a distinction no user of a ledger
411/// means to draw.
412impl PartialEq for Decimal {
413    fn eq(&self, other: &Decimal) -> bool {
414        self.cmp(other) == Ordering::Equal
415    }
416}
417
418impl Eq for Decimal {}
419
420/// A total order, which two exact numbers always have.
421///
422/// Where the scales cannot be aligned without overflowing, the numbers
423/// are compared by sign and then by how many digits they have before
424/// the point, which orders them correctly because a number with more
425/// whole digits is the larger one.
426impl Ord for Decimal {
427    fn cmp(&self, other: &Decimal) -> Ordering {
428        if let Some((a, b)) = align(self, other) {
429            return a.unscaled.cmp(&b.unscaled);
430        }
431        let sign = self.unscaled.signum().cmp(&other.unscaled.signum());
432        if sign != Ordering::Equal {
433            return sign;
434        }
435        let whole = |d: &Decimal| i32::from(d.digits()) - i32::from(d.scale);
436        let by_size = whole(self).cmp(&whole(other));
437        match self.unscaled.is_negative() {
438            true => by_size.reverse(),
439            false => by_size,
440        }
441    }
442}
443
444impl PartialOrd for Decimal {
445    fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> {
446        Some(self.cmp(other))
447    }
448}
449
450impl std::hash::Hash for Decimal {
451    /// Hashed on the number and not on the pair, so that two values
452    /// which compare equal hash alike and a decimal can key a group.
453    ///
454    /// The normal form is the unscaled integer with its trailing
455    /// noughts taken off, which every spelling of one number reduces
456    /// to.
457    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
458        let (mut unscaled, mut scale) = (self.unscaled, i64::from(self.scale));
459        while unscaled != 0 && unscaled % 10 == 0 {
460            unscaled /= 10;
461            scale -= 1;
462        }
463        unscaled.hash(state);
464        match unscaled {
465            0 => 0i64.hash(state),
466            _ => scale.hash(state),
467        }
468    }
469}
470
471/// Written the way it was declared: the digits with a point put in at
472/// the scale, and no exponent, since an exact number is written out.
473impl fmt::Display for Decimal {
474    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475        if self.scale == 0 {
476            return write!(f, "{}", self.unscaled);
477        }
478        let digits = self.unscaled.unsigned_abs().to_string();
479        let places = usize::from(self.scale);
480        let sign = match self.unscaled.is_negative() {
481            true => "-",
482            false => "",
483        };
484        // A number smaller than one has no whole digits of its own, so
485        // the nought before the point and the noughts after it are put
486        // there rather than taken from the digits.
487        if digits.len() <= places {
488            let pad = "0".repeat(places - digits.len());
489            return write!(f, "{sign}0.{pad}{digits}");
490        }
491        let (whole, fraction) = digits.split_at(digits.len() - places);
492        write!(f, "{sign}{whole}.{fraction}")
493    }
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499
500    #[test]
501    fn a_decimal_prints_at_the_scale_it_was_written_with() {
502        assert_eq!(Decimal::new(120, 2).to_string(), "1.20");
503        assert_eq!(Decimal::new(12, 1).to_string(), "1.2");
504        assert_eq!(Decimal::new(12, 0).to_string(), "12");
505        assert_eq!(Decimal::new(-120, 2).to_string(), "-1.20");
506        // Fewer digits than places, so the nought and the padding are
507        // written rather than taken out of the digits.
508        assert_eq!(Decimal::new(5, 3).to_string(), "0.005");
509        assert_eq!(Decimal::new(-5, 3).to_string(), "-0.005");
510        assert_eq!(Decimal::new(0, 2).to_string(), "0.00");
511    }
512
513    #[test]
514    fn two_spellings_of_one_number_are_one_value() {
515        let (loose, tight) = (Decimal::new(12, 1), Decimal::new(120, 2));
516        assert_eq!(loose, tight);
517        assert_eq!(loose.cmp(&tight), Ordering::Equal);
518        // And they hash alike, which is what lets one key a group.
519        let hash = |d: &Decimal| {
520            use std::hash::{Hash, Hasher};
521            let mut h = std::collections::hash_map::DefaultHasher::new();
522            d.hash(&mut h);
523            h.finish()
524        };
525        assert_eq!(hash(&loose), hash(&tight));
526        assert_eq!(hash(&Decimal::new(0, 0)), hash(&Decimal::new(0, 7)));
527        // They print differently all the same, because the scale is
528        // how precisely the number is known.
529        assert_ne!(loose.to_string(), tight.to_string());
530    }
531
532    #[test]
533    fn a_tenth_and_two_tenths_are_three_tenths() {
534        let (a, b) = (
535            Decimal::parse("0.1", 1).unwrap(),
536            Decimal::parse("0.2", 1).unwrap(),
537        );
538        assert_eq!(a.add(&b).unwrap().to_string(), "0.3");
539        // Which is the whole point: the same two numbers taken as
540        // binary64 do not add up to three tenths, and no arrangement of
541        // the sum makes them.
542        assert_ne!(a.to_f64() + b.to_f64(), 0.3f64);
543    }
544
545    #[test]
546    fn arithmetic_answers_at_the_scale_the_units_give() {
547        let (a, b) = (Decimal::new(150, 2), Decimal::new(3, 1));
548        // A hundredth plus a tenth is a number of hundredths.
549        assert_eq!(a.add(&b).unwrap().to_string(), "1.80");
550        assert_eq!(a.sub(&b).unwrap().to_string(), "1.20");
551        // Multiplying the units multiplies the scale.
552        assert_eq!(a.mul(&b).unwrap().to_string(), "0.450");
553        assert_eq!(a.rem(&b).unwrap().to_string(), "0.00");
554        assert_eq!(a.negate().unwrap().to_string(), "-1.50");
555    }
556
557    #[test]
558    fn a_quotient_is_carried_as_far_as_the_operands_knew() {
559        let third = Decimal::new(1, 0).div(&Decimal::new(3, 0)).unwrap();
560        assert_eq!(third.to_string(), "0.333333");
561        // Rounded half away from zero at the last digit kept.
562        assert_eq!(
563            Decimal::new(2, 0)
564                .div(&Decimal::new(3, 0))
565                .unwrap()
566                .to_string(),
567            "0.666667"
568        );
569        assert_eq!(
570            Decimal::new(-2, 0)
571                .div(&Decimal::new(3, 0))
572                .unwrap()
573                .to_string(),
574            "-0.666667"
575        );
576        // A price split three ways still says what a person would.
577        let each = Decimal::new(1000, 2).div(&Decimal::new(4, 0)).unwrap();
578        assert_eq!(each.rescale(2).unwrap().to_string(), "2.50");
579        assert_eq!(Decimal::new(1, 0).div(&Decimal::new(0, 0)), None);
580    }
581
582    #[test]
583    fn text_is_read_at_the_scale_it_is_wanted_at() {
584        assert_eq!(Decimal::parse("1.20", 2).unwrap(), Decimal::new(120, 2));
585        assert_eq!(
586            Decimal::parse("  -3.5 ", 3).unwrap(),
587            Decimal::new(-3500, 3)
588        );
589        assert_eq!(Decimal::parse("12", 2).unwrap(), Decimal::new(1200, 2));
590        assert_eq!(Decimal::parse(".5", 1).unwrap(), Decimal::new(5, 1));
591        assert_eq!(Decimal::parse("5.", 1).unwrap(), Decimal::new(50, 1));
592        // An exponent moves the point rather than going through a float.
593        assert_eq!(Decimal::parse("1E3", 0).unwrap(), Decimal::new(1000, 0));
594        assert_eq!(Decimal::parse("15e-2", 2).unwrap(), Decimal::new(15, 2));
595        // Past the scale it rounds half away from zero.
596        assert_eq!(Decimal::parse("1.005", 2).unwrap(), Decimal::new(101, 2));
597        assert_eq!(Decimal::parse("-1.005", 2).unwrap(), Decimal::new(-101, 2));
598        assert_eq!(Decimal::parse("1.004", 2).unwrap(), Decimal::new(100, 2));
599        for not_a_number in ["", ".", "x", "1.2.3", "1,000", "1e", "0x10"] {
600            assert_eq!(Decimal::parse(not_a_number, 2), None, "{not_a_number}");
601        }
602    }
603
604    #[test]
605    fn a_rescale_that_would_not_be_exact_is_refused() {
606        let value = Decimal::new(125, 2);
607        assert_eq!(value.rescale(4).unwrap(), Decimal::new(12500, 4));
608        assert_eq!(value.rescale(2).unwrap(), value);
609        // Two places down to one would throw away a five.
610        assert_eq!(value.rescale(1), None);
611        assert_eq!(
612            Decimal::new(120, 2).rescale(1).unwrap(),
613            Decimal::new(12, 1)
614        );
615    }
616
617    #[test]
618    fn rounding_stops_at_the_place_it_was_asked_for() {
619        let value = Decimal::parse("1.005", 3).unwrap();
620        // The float this reads as is a shade under a thousand and five
621        // thousandths, so a float would round it down. An exact number
622        // has the five and rounds up.
623        assert_eq!(value.round(2).unwrap().to_string(), "1.01");
624        assert_eq!(value.round(0).unwrap().to_string(), "1");
625        assert_eq!(value.round(5).unwrap().to_string(), "1.00500");
626    }
627
628    #[test]
629    fn halves_go_away_from_nought_on_both_sides_of_it() {
630        assert_eq!(Decimal::new(25, 1).round(0).unwrap().to_string(), "3");
631        assert_eq!(Decimal::new(-25, 1).round(0).unwrap().to_string(), "-3");
632        assert_eq!(Decimal::new(35, 1).round(0).unwrap().to_string(), "4");
633    }
634
635    #[test]
636    fn a_negative_digit_count_rounds_to_the_left_of_the_point() {
637        // Minus one is the tens, so this drops the half and the five
638        // under it stays where it is.
639        assert_eq!(Decimal::new(1505, 1).round(-1).unwrap().to_string(), "150");
640        // Minus two is the hundreds, and now the fifty is the half.
641        assert_eq!(Decimal::new(150, 0).round(-2).unwrap().to_string(), "200");
642        assert_eq!(Decimal::new(-150, 0).round(-2).unwrap().to_string(), "-200");
643        assert_eq!(Decimal::new(149, 0).round(-2).unwrap().to_string(), "100");
644    }
645
646    #[test]
647    fn a_ceiling_and_a_floor_lean_the_same_way_for_both_signs() {
648        let up = Decimal::new(15, 1);
649        let down = Decimal::new(-15, 1);
650        assert_eq!(up.ceil(0).unwrap().to_string(), "2");
651        assert_eq!(up.floor(0).unwrap().to_string(), "1");
652        // Toward positive infinity is toward nought here, which is what
653        // separates a ceiling from rounding away from nought.
654        assert_eq!(down.ceil(0).unwrap().to_string(), "-1");
655        assert_eq!(down.floor(0).unwrap().to_string(), "-2");
656        // Nothing to drop, so nothing moves.
657        assert_eq!(Decimal::new(2, 0).ceil(0).unwrap().to_string(), "2");
658    }
659
660    #[test]
661    fn the_digit_count_is_of_the_number_and_not_of_the_declaration() {
662        assert_eq!(Decimal::new(0, 4).digits(), 1);
663        assert_eq!(Decimal::new(9, 0).digits(), 1);
664        assert_eq!(Decimal::new(10, 0).digits(), 2);
665        assert_eq!(Decimal::new(-999, 2).digits(), 3);
666        assert_eq!(Decimal::new(i128::MAX, 0).digits(), 39);
667    }
668
669    #[test]
670    fn ordering_holds_where_the_scales_cannot_be_aligned() {
671        // Aligning these would overflow, so the order comes from the
672        // sign and the count of whole digits.
673        let huge = Decimal::new(i128::MAX, 0);
674        let small = Decimal::new(1, MAX_DIGITS);
675        assert_eq!(huge.cmp(&small), Ordering::Greater);
676        assert_eq!(small.cmp(&huge), Ordering::Less);
677        assert_eq!(
678            huge.negate().unwrap().cmp(&small.negate().unwrap()),
679            Ordering::Less
680        );
681        assert_eq!(Decimal::new(0, 0).cmp(&small), Ordering::Less);
682    }
683}