lucre 0.10.0

An ergonomic library for handling money.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Rendering of [`Money`] values as text.

use std::fmt::{self, Write as _};

use crate::{Money, RoundingMode};

/// A reusable recipe for rendering monetary amounts, applied by
/// [`Money::format_with`].
///
/// Start from [`Format::new`] (or [`Format::default`]) and refine it with the
/// builder methods; every combination of options is valid, so neither
/// construction nor formatting can fail.
///
/// The vocabulary is deliberately locale-ignorant. It can express most
/// national conventions, but knows nothing about locales themselves, so
/// choosing a convention for a given audience is left to the caller.
///
/// ## Example
///
/// ```
/// use lucre::{Currency, Format, Money};
///
/// // The starting recipe groups digits in threes by commas, marks the
/// // fraction with a dot and pads it to the currency's minor digits, gives
/// // negatives a leading minus, and suffixes the ISO code.
/// let money = Money::from_minor(150000, &Currency::USD);
///
/// assert_eq!(money.format_with(&Format::new()).to_string(), "1,500.00 USD");
///
/// // Continental European conventions are a few calls away.
/// let price = Money::from_minor(-150000, &Currency::EUR);
/// let format = Format::new().symbol().parentheses().separators('.', ',');
///
/// assert_eq!(price.format_with(&format).to_string(), "(€1.500,00)");
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Format {
    identifier: Identifier,
    position: Option<Position>,
    spaced: Option<bool>,
    negative: NegativeStyle,
    precision: Option<(u32, RoundingMode)>,
    grouping: &'static [u8],
    group_separator: char,
    decimal_separator: char,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum Identifier {
    Code,
    Symbol,
    None,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum Position {
    Prefix,
    Suffix,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum NegativeStyle {
    Minus,
    Parentheses,
}

impl Format {
    /// The starting recipe.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// assert_eq!(money.format_with(&Format::new()).to_string(), "1,500.00 USD");
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            identifier: Identifier::Code,
            position: None,
            spaced: None,
            negative: NegativeStyle::Minus,
            precision: None,
            grouping: &[3],
            group_separator: ',',
            decimal_separator: '.',
        }
    }

    /// Identify the currency by its three-letter ISO code — suffixed, with a
    /// space, unless overridden.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// assert_eq!(
    ///     money.format_with(&Format::new().code()).to_string(),
    ///     "1,500.00 USD"
    /// );
    /// ```
    #[must_use]
    pub const fn code(mut self) -> Self {
        self.identifier = Identifier::Code;
        self
    }

    /// Identify the currency by its symbol — prefixed, without a space,
    /// unless overridden.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// assert_eq!(
    ///     money.format_with(&Format::new().symbol()).to_string(),
    ///     "$1,500.00"
    /// );
    /// ```
    #[must_use]
    pub const fn symbol(mut self) -> Self {
        self.identifier = Identifier::Symbol;
        self
    }

    /// Show the bare amount with no currency identifier.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// assert_eq!(
    ///     money.format_with(&Format::new().amount_only()).to_string(),
    ///     "1,500.00"
    /// );
    /// ```
    #[must_use]
    pub const fn amount_only(mut self) -> Self {
        self.identifier = Identifier::None;
        self
    }

    /// Place the currency identifier before the amount.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// // A code sits after the amount unless placed otherwise.
    /// assert_eq!(
    ///     money.format_with(&Format::new().prefix()).to_string(),
    ///     "USD 1,500.00"
    /// );
    /// ```
    #[must_use]
    pub const fn prefix(mut self) -> Self {
        self.position = Some(Position::Prefix);
        self
    }

    /// Place the currency identifier after the amount.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// // A symbol sits before the amount unless placed otherwise.
    /// assert_eq!(
    ///     money.format_with(&Format::new().symbol().suffix()).to_string(),
    ///     "1,500.00$"
    /// );
    /// ```
    #[must_use]
    pub const fn suffix(mut self) -> Self {
        self.position = Some(Position::Suffix);
        self
    }

    /// Put a space between the amount and the currency identifier.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// assert_eq!(
    ///     money.format_with(&Format::new().symbol().spaced()).to_string(),
    ///     "$ 1,500.00"
    /// );
    /// ```
    #[must_use]
    pub const fn spaced(mut self) -> Self {
        self.spaced = Some(true);
        self
    }

    /// Join the currency identifier directly to the amount.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::USD);
    ///
    /// assert_eq!(
    ///     money.format_with(&Format::new().no_space()).to_string(),
    ///     "1,500.00USD"
    /// );
    /// ```
    #[must_use]
    pub const fn no_space(mut self) -> Self {
        self.spaced = Some(false);
        self
    }

    /// Mark negative amounts with a leading minus sign.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let debt = Money::from_minor(-150000, &Currency::USD);
    /// let format = Format::new().symbol().minus_sign();
    ///
    /// assert_eq!(debt.format_with(&format).to_string(), "-$1,500.00");
    /// ```
    #[must_use]
    pub const fn minus_sign(mut self) -> Self {
        self.negative = NegativeStyle::Minus;
        self
    }

    /// Mark negative amounts accounting-style, wrapping the whole rendering
    /// in parentheses.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let debt = Money::from_minor(-150000, &Currency::USD);
    /// let format = Format::new().symbol().parentheses();
    ///
    /// assert_eq!(debt.format_with(&format).to_string(), "($1,500.00)");
    /// ```
    #[must_use]
    pub const fn parentheses(mut self) -> Self {
        self.negative = NegativeStyle::Parentheses;
        self
    }

    /// Render exactly `digits` fractional digits, rounding with `mode` when
    /// the amount carries more.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Format, Money, RoundingMode};
    ///
    /// let money = Money::from_decimal("2.675".parse()?, &Currency::USD);
    ///
    /// let format = Format::new().precision(2, RoundingMode::HalfUp);
    /// assert_eq!(money.format_with(&format).to_string(), "2.68 USD");
    ///
    /// // Without `precision`, the fraction is padded to the currency's
    /// // minor digits, excess digits are shown in full, and nothing is
    /// // ever rounded.
    /// assert_eq!(money.format_with(&Format::new()).to_string(), "2.675 USD");
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn precision(mut self, digits: u32, mode: RoundingMode) -> Self {
        self.precision = Some((digits, mode));
        self
    }

    /// Group the integer digits by `pattern`, counted from the decimal mark
    /// outward, with the last entry repeating.
    ///
    /// An empty pattern (or a zero entry, once reached) leaves the remaining
    /// digits unbroken.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_major(1234567, &Currency::INR);
    ///
    /// let western = Format::new().grouping(&[3]);
    /// assert_eq!(money.format_with(&western).to_string(), "1,234,567.00 INR");
    ///
    /// let indian = Format::new().grouping(&[3, 2]);
    /// assert_eq!(money.format_with(&indian).to_string(), "12,34,567.00 INR");
    /// ```
    #[must_use]
    pub const fn grouping(mut self, pattern: &'static [u8]) -> Self {
        self.grouping = pattern;
        self
    }

    /// Render the integer digits as one unbroken run.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_major(1234567, &Currency::USD);
    ///
    /// assert_eq!(
    ///     money.format_with(&Format::new().no_grouping()).to_string(),
    ///     "1234567.00 USD"
    /// );
    /// ```
    #[must_use]
    pub const fn no_grouping(mut self) -> Self {
        self.grouping = &[];
        self
    }

    /// The characters that separate digit groups and mark the start of the
    /// fraction.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150000, &Currency::EUR);
    /// let format = Format::new().separators('.', ',');
    ///
    /// assert_eq!(money.format_with(&format).to_string(), "1.500,00 EUR");
    /// ```
    #[must_use]
    pub const fn separators(mut self, group: char, decimal: char) -> Self {
        self.group_separator = group;
        self.decimal_separator = decimal;
        self
    }
}

impl Default for Format {
    fn default() -> Self {
        Self::new()
    }
}

impl Money {
    /// Renders this amount as `format` describes.
    ///
    /// The result is a value for `write!`/`format!`/`to_string`, so nothing
    /// is allocated until it is actually displayed.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Format, Money};
    ///
    /// let money = Money::from_minor(150, &Currency::USD);
    /// let bare = Format::new().amount_only();
    ///
    /// // Width, fill, and alignment flags are honored; with no explicit
    /// // alignment the amount aligns right, like the numeric types.
    /// assert_eq!(format!("{:8}", money.format_with(&bare)), "    1.50");
    /// assert_eq!(format!("{:*^8}", money.format_with(&bare)), "**1.50**");
    ///
    /// // The `{:.N}` flag is ignored — fractional digits are set via
    /// // `Format::precision`, which insists on a rounding mode.
    /// assert_eq!(format!("{:.1}", money.format_with(&bare)), "1.50");
    /// ```
    #[must_use]
    pub fn format_with(&self, format: &Format) -> impl fmt::Display + use<> {
        Formatted {
            money: *self,
            format: *format,
        }
    }
}

/// Renders as [`Format::default`] describes.
///
/// ## Example
///
/// ```
/// use lucre::{Currency, Money};
///
/// let money = Money::from_minor(150000, &Currency::USD);
///
/// assert_eq!(money.to_string(), "1,500.00 USD");
/// ```
impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.format_with(&Format::default()), f)
    }
}

struct Formatted {
    money: Money,
    format: Format,
}

impl fmt::Display for Formatted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_padded(f, &self.render())
    }
}

/// Writes already-rendered text under the `{:width}`, `{:fill}`, and
/// alignment flags, defaulting to right alignment as the numeric types do.
///
/// Padding is applied by hand rather than through [`fmt::Formatter::pad`],
/// which would also honor `{:.N}` and truncate mid-number.
pub(crate) fn write_padded(f: &mut fmt::Formatter<'_>, rendered: &str) -> fmt::Result {
    let Some(width) = f.width() else {
        return f.write_str(rendered);
    };

    let length = rendered.chars().count();
    if length >= width {
        return f.write_str(rendered);
    }
    let padding = width - length;
    let (left, right) = match f.align().unwrap_or(fmt::Alignment::Right) {
        fmt::Alignment::Left => (0, padding),
        fmt::Alignment::Right => (padding, 0),
        fmt::Alignment::Center => (padding / 2, padding - padding / 2),
    };
    let fill = f.fill();
    for _ in 0..left {
        f.write_char(fill)?;
    }
    f.write_str(rendered)?;
    for _ in 0..right {
        f.write_char(fill)?;
    }
    Ok(())
}

impl Formatted {
    fn render(&self) -> String {
        let currency = self.money.currency();
        let format = &self.format;

        let amount = match format.precision {
            Some((digits, mode)) => self.money.round(digits, mode).amount(),
            None => self.money.amount(),
        };
        // A sign is only rendered when it will precede nonzero digits, so an
        // amount that is (or rounds to) negative zero shows no sign at all.
        let negative = amount.is_sign_negative() && !amount.is_zero();

        let fraction_digits = match format.precision {
            Some((digits, _)) => digits,
            None => amount.scale().max(currency.minor_digits()),
        } as usize;

        let magnitude = amount.abs();
        let scale = magnitude.scale() as usize;
        let mut digits = magnitude.mantissa().to_string();
        while digits.len() <= scale {
            digits.insert(0, '0');
        }
        let (integer, fraction) = digits.split_at(digits.len() - scale);

        let mut number = group_digits(integer, format.grouping, format.group_separator);
        if fraction_digits > 0 {
            number.push(format.decimal_separator);
            number.push_str(fraction);
            for _ in fraction.len()..fraction_digits {
                number.push('0');
            }
        }

        let code = currency.alphabetic_code();
        let (identifier, position, spaced) = match format.identifier {
            Identifier::Code => (
                Some(code.as_str()),
                format.position.unwrap_or(Position::Suffix),
                format.spaced.unwrap_or(true),
            ),
            Identifier::Symbol => (
                Some(currency.symbol()),
                format.position.unwrap_or(Position::Prefix),
                format.spaced.unwrap_or(false),
            ),
            Identifier::None => (None, Position::Prefix, false),
        };

        let mut out = String::new();
        let parenthesized = negative && matches!(format.negative, NegativeStyle::Parentheses);
        if parenthesized {
            out.push('(');
        } else if negative {
            out.push('-');
        }
        match (identifier, position) {
            (Some(identifier), Position::Prefix) => {
                out.push_str(identifier);
                if spaced {
                    out.push(' ');
                }
                out.push_str(&number);
            }
            (Some(identifier), Position::Suffix) => {
                out.push_str(&number);
                if spaced {
                    out.push(' ');
                }
                out.push_str(identifier);
            }
            (None, _) => out.push_str(&number),
        }
        if parenthesized {
            out.push(')');
        }
        out
    }
}

/// Splits a run of integer digits into separator-joined groups sized by
/// `pattern`, working from the rightmost digit outward with the last pattern
/// entry repeating indefinitely.
fn group_digits(digits: &str, pattern: &[u8], separator: char) -> String {
    let mut groups = Vec::new();
    let mut rest = digits.as_bytes();
    let mut sizes = pattern.iter().copied();
    let mut size = sizes.next().unwrap_or(0) as usize;
    while size != 0 && rest.len() > size {
        let (head, group) = rest.split_at(rest.len() - size);
        groups.push(group);
        rest = head;
        size = sizes.next().map_or(size, |s| s as usize);
    }

    let ascii = |bytes| std::str::from_utf8(bytes).expect("digits are ASCII");
    let mut out = String::from(ascii(rest));
    for group in groups.into_iter().rev() {
        out.push(separator);
        out.push_str(ascii(group));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Currency;
    use rust_decimal::prelude::*;

    #[test]
    fn default_format_test() {
        let money = Money::from_minor(150000, &Currency::USD);

        assert_eq!(money.to_string(), "1,500.00 USD");
    }

    #[test]
    fn pads_fraction_to_minor_digits_test() {
        assert_eq!(
            Money::from_major(-3, &Currency::USD).to_string(),
            "-3.00 USD"
        );
    }

    #[test]
    fn zero_minor_digits_omit_decimal_mark_test() {
        assert_eq!(Money::from_major(5, &Currency::JPY).to_string(), "5 JPY");
    }

    #[test]
    fn excess_precision_is_shown_in_full_test() {
        let money = Money::from_decimal(dec!(1.2345), &Currency::USD);

        assert_eq!(money.to_string(), "1.2345 USD");
    }

    #[test]
    fn symbol_test() {
        let money = Money::from_minor(150000, &Currency::USD);

        assert_eq!(
            money.format_with(&Format::new().symbol()).to_string(),
            "$1,500.00"
        );
    }

    #[test]
    fn symbol_suffix_spaced_test() {
        let money = Money::from_minor(150, &Currency::USD);
        let format = Format::new().symbol().suffix().spaced();

        assert_eq!(money.format_with(&format).to_string(), "1.50 $");
    }

    #[test]
    fn code_prefix_test() {
        let money = Money::from_minor(150000, &Currency::USD);
        let format = Format::new().prefix();

        assert_eq!(money.format_with(&format).to_string(), "USD 1,500.00");
    }

    #[test]
    fn code_no_space_test() {
        let money = Money::from_minor(150, &Currency::USD);
        let format = Format::new().no_space();

        assert_eq!(money.format_with(&format).to_string(), "1.50USD");
    }

    #[test]
    fn amount_only_test() {
        let money = Money::from_minor(150000, &Currency::USD);

        assert_eq!(
            money.format_with(&Format::new().amount_only()).to_string(),
            "1,500.00"
        );
    }

    #[test]
    fn negative_symbol_test() {
        let money = Money::from_minor(-150000, &Currency::USD);

        assert_eq!(
            money.format_with(&Format::new().symbol()).to_string(),
            "-$1,500.00"
        );
    }

    #[test]
    fn parentheses_test() {
        let format = Format::new().symbol().parentheses();
        let negative = Money::from_minor(-150000, &Currency::USD);
        let positive = Money::from_minor(150000, &Currency::USD);

        assert_eq!(negative.format_with(&format).to_string(), "($1,500.00)");
        assert_eq!(positive.format_with(&format).to_string(), "$1,500.00");
    }

    #[test]
    fn minus_sign_restores_default_test() {
        let money = Money::from_minor(-150, &Currency::USD);
        let format = Format::new().parentheses().minus_sign();

        assert_eq!(money.format_with(&format).to_string(), "-1.50 USD");
    }

    #[test]
    fn precision_rounds_test() {
        let money = Money::from_decimal(dec!(2.675), &Currency::USD);

        assert_eq!(
            money
                .format_with(&Format::new().precision(2, RoundingMode::HalfUp))
                .to_string(),
            "2.68 USD"
        );
        assert_eq!(
            money
                .format_with(&Format::new().precision(2, RoundingMode::HalfDown))
                .to_string(),
            "2.67 USD"
        );
    }

    #[test]
    fn precision_pads_test() {
        let money = Money::from_major(1, &Currency::USD);
        let format = Format::new().precision(4, RoundingMode::HalfEven);

        assert_eq!(money.format_with(&format).to_string(), "1.0000 USD");
    }

    #[test]
    fn precision_zero_digits_test() {
        let money = Money::from_decimal(dec!(1500.5), &Currency::USD);
        let format = Format::new().precision(0, RoundingMode::HalfUp);

        assert_eq!(money.format_with(&format).to_string(), "1,501 USD");
    }

    #[test]
    fn rounded_to_zero_shows_no_sign_test() {
        let money = Money::from_decimal(dec!(-0.004), &Currency::USD);

        assert_eq!(
            money
                .format_with(&Format::new().precision(2, RoundingMode::HalfEven))
                .to_string(),
            "0.00 USD"
        );
        assert_eq!(
            money
                .format_with(
                    &Format::new()
                        .parentheses()
                        .precision(2, RoundingMode::HalfEven)
                )
                .to_string(),
            "0.00 USD"
        );
    }

    #[test]
    fn indian_grouping_test() {
        let money = Money::from_decimal(dec!(12345678.90), &Currency::INR);
        let format = Format::new().grouping(&[3, 2]);

        assert_eq!(money.format_with(&format).to_string(), "1,23,45,678.90 INR");
    }

    #[test]
    fn no_grouping_test() {
        let money = Money::from_major(1234567, &Currency::USD);
        let format = Format::new().no_grouping();

        assert_eq!(money.format_with(&format).to_string(), "1234567.00 USD");
    }

    #[test]
    fn separators_test() {
        let money = Money::from_minor(150000, &Currency::EUR);
        let format = Format::new().separators('.', ',');

        assert_eq!(money.format_with(&format).to_string(), "1.500,00 EUR");
    }

    #[test]
    fn width_and_alignment_test() {
        let money = Money::from_minor(150, &Currency::USD);
        let bare = Format::new().amount_only();

        assert_eq!(format!("{:8}", money.format_with(&bare)), "    1.50");
        assert_eq!(format!("{:<8}", money.format_with(&bare)), "1.50    ");
        assert_eq!(format!("{:*^8}", money.format_with(&bare)), "**1.50**");
    }

    #[test]
    fn display_honors_width_test() {
        let money = Money::from_minor(150, &Currency::USD);

        assert_eq!(format!("{money:>12}"), "    1.50 USD");
    }

    #[test]
    fn fmt_precision_flag_is_ignored_test() {
        let money = Money::from_minor(150, &Currency::USD);

        assert_eq!(format!("{money:.1}"), "1.50 USD");
    }
}