Skip to main content

ggplot_rs/
locale.rs

1//! Locale conventions for number and date labels.
2//!
3//! A [`Locale`] bundles the decimal / thousands marks, the currency and
4//! percent conventions and the month / weekday names of a region. It is used
5//!
6//! - explicitly, by the `label_*_locale` formatters in
7//!   [`crate::scale::format`] (e.g. [`label_currency_locale`]);
8//! - plot-wide, via [`GGPlot::locale`](crate::GGPlot::locale): every default
9//!   continuous axis and legend then labels its breaks with the locale's
10//!   marks, and date/datetime scales use its month names and date formats;
11//! - per scale, via `ScaleContinuous::with_locale` /
12//!   `ScaleDateTime::with_locale` (overrides the plot locale).
13//!
14//! Without a locale nothing changes: labels keep the `.` decimal mark, no
15//! thousands grouping on default axes, and ISO dates.
16//!
17//! ```
18//! use ggplot_rs::locale::Locale;
19//! use ggplot_rs::scale::format::label_currency_locale;
20//! let de = Locale::from_tag("de-DE");
21//! assert_eq!(label_currency_locale(&de, Some(0.01))(1234.5), "1.234,50 €");
22//! let us = Locale::en_us();
23//! assert_eq!(label_currency_locale(&us, Some(0.01))(1234.5), "$1,234.50");
24//! assert_eq!(de.strftime(1_792_022_400, "%-d. %b %Y"), "15. Okt. 2026");
25//! ```
26//!
27//! [`label_currency_locale`]: crate::scale::format::label_currency_locale
28
29/// Where a locale puts the currency symbol relative to the amount.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum CurrencyPosition {
32    /// Symbol before the amount (`$1,234.50`, `£5`).
33    Prefix,
34    /// Symbol after the amount (`1.234,50 €`).
35    Suffix,
36}
37
38/// Number and date formatting conventions of a locale.
39///
40/// Construct one with a preset ([`en_us`](Self::en_us), [`de_de`](Self::de_de),
41/// [`fr_fr`](Self::fr_fr), [`en_gb`](Self::en_gb)) or [`from_tag`](Self::from_tag),
42/// then adjust the public fields or use the `with_*` builders. The struct is
43/// `#[non_exhaustive]` so new conventions can be added without a breaking
44/// change.
45#[derive(Clone, Debug, PartialEq)]
46#[non_exhaustive]
47pub struct Locale {
48    /// Canonical BCP-47 tag of the preset, e.g. `"de-DE"`.
49    pub tag: String,
50    /// Decimal mark (`"."` / `","`).
51    pub decimal_mark: String,
52    /// Thousands separator (`","`, `"."`, `" "`, `"'"`; `""` disables grouping).
53    pub big_mark: String,
54    /// Group thousands only when the integer part has at least
55    /// `3 + min_grouping_digits` digits (CLDR's minimum grouping digits).
56    /// `1` (every preset) groups `1000` as `1.000`; `2` leaves `2020` alone
57    /// and groups from `10.000`.
58    pub min_grouping_digits: usize,
59    /// The locale's currency symbol (`"$"`, `"€"`, `"£"`).
60    pub currency_symbol: String,
61    /// Where the currency symbol goes.
62    pub currency_position: CurrencyPosition,
63    /// Text between amount and currency symbol (`""` or `" "`).
64    pub currency_spacing: String,
65    /// Suffix of percentages (`"%"` in English, `" %"` in German / French).
66    pub percent_suffix: String,
67    /// Abbreviated month names, January first (`%b`).
68    pub months_short: [String; 12],
69    /// Full month names, January first (`%B`).
70    pub months_long: [String; 12],
71    /// Abbreviated weekday names, Sunday first (`%a`).
72    pub days_short: [String; 7],
73    /// Full weekday names, Sunday first (`%A`).
74    pub days_long: [String; 7],
75    /// strftime format of a calendar date (default date-axis labels at day
76    /// resolution), e.g. `"%-d. %b %Y"` → `15. Okt. 2026`.
77    pub date_format: String,
78    /// strftime format of a month (default monthly date-axis labels), e.g.
79    /// `"%b %Y"` → `Okt. 2026`.
80    pub month_format: String,
81    /// strftime format of a time of day, appended to the date for datetimes
82    /// that are not at midnight, e.g. `"%H:%M"`.
83    pub time_format: String,
84}
85
86/// CLDR-derived presets beyond the hand-written four (#538 follow-up,
87/// DataZooDE/anofox-visualization#1358): marks, currency placement, month
88/// and weekday names and date patterns as ICU formats them. Thousands marks
89/// that CLDR writes as a (narrow) no-break space are a plain space, as in
90/// [`Locale::fr_fr`].
91struct Preset {
92    tag: &'static str,
93    decimal: &'static str,
94    big: &'static str,
95    currency: &'static str,
96    spacing: &'static str,
97    percent: &'static str,
98    date: &'static str,
99    month: &'static str,
100    min_grouping: usize,
101    suffix: bool,
102    months_short: [&'static str; 12],
103    months_long: [&'static str; 12],
104    days_short: [&'static str; 7],
105    days_long: [&'static str; 7],
106}
107
108#[rustfmt::skip]
109const PRESETS: &[Preset] = &[
110    Preset {
111        tag: "de-AT", decimal: ",", big: " ", min_grouping: 1,
112        currency: "€", suffix: false, spacing: " ", percent: " %",
113        months_short: ["Jän.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sep.", "Okt.", "Nov.", "Dez."],
114        months_long: ["Jänner", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
115        days_short: ["So.", "Mo.", "Di.", "Mi.", "Do.", "Fr.", "Sa."],
116        days_long: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
117        date: "%-d. %b %Y", month: "%b %Y",
118    },
119    Preset {
120        tag: "de-CH", decimal: ".", big: "'", min_grouping: 1,
121        currency: "CHF", suffix: false, spacing: " ", percent: "%",
122        months_short: ["Jan.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.", "Nov.", "Dez."],
123        months_long: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
124        days_short: ["So.", "Mo.", "Di.", "Mi.", "Do.", "Fr.", "Sa."],
125        days_long: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
126        date: "%-d. %b %Y", month: "%b %Y",
127    },
128    Preset {
129        tag: "fr-BE", decimal: ",", big: " ", min_grouping: 1,
130        currency: "€", suffix: true, spacing: " ", percent: " %",
131        months_short: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."],
132        months_long: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
133        days_short: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."],
134        days_long: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],
135        date: "%-d %b %Y", month: "%b %Y",
136    },
137    Preset {
138        tag: "fr-CH", decimal: ",", big: " ", min_grouping: 1,
139        currency: "CHF", suffix: true, spacing: " ", percent: "%",
140        months_short: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."],
141        months_long: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
142        days_short: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."],
143        days_long: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],
144        date: "%-d %b %Y", month: "%b %Y",
145    },
146    Preset {
147        tag: "fr-CA", decimal: ",", big: " ", min_grouping: 1,
148        currency: "$", suffix: true, spacing: " ", percent: " %",
149        months_short: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juill.", "août", "sept.", "oct.", "nov.", "déc."],
150        months_long: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
151        days_short: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."],
152        days_long: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],
153        date: "%-d %b %Y", month: "%b %Y",
154    },
155    Preset {
156        tag: "it-IT", decimal: ",", big: ".", min_grouping: 2,
157        currency: "€", suffix: true, spacing: " ", percent: "%",
158        months_short: ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"],
159        months_long: ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"],
160        days_short: ["dom", "lun", "mar", "mer", "gio", "ven", "sab"],
161        days_long: ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"],
162        date: "%-d %b %Y", month: "%b %Y",
163    },
164    Preset {
165        tag: "it-CH", decimal: ".", big: "'", min_grouping: 2,
166        currency: "CHF", suffix: false, spacing: " ", percent: "%",
167        months_short: ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"],
168        months_long: ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"],
169        days_short: ["dom", "lun", "mar", "mer", "gio", "ven", "sab"],
170        days_long: ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"],
171        date: "%-d %b %Y", month: "%b %Y",
172    },
173    Preset {
174        tag: "es-ES", decimal: ",", big: ".", min_grouping: 2,
175        currency: "€", suffix: true, spacing: " ", percent: " %",
176        months_short: ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sept", "oct", "nov", "dic"],
177        months_long: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
178        days_short: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
179        days_long: ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"],
180        date: "%-d %b %Y", month: "%b %Y",
181    },
182    Preset {
183        tag: "es-MX", decimal: ".", big: ",", min_grouping: 1,
184        currency: "$", suffix: false, spacing: "", percent: "%",
185        months_short: ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"],
186        months_long: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
187        days_short: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
188        days_long: ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"],
189        date: "%-d %b %Y", month: "%b %Y",
190    },
191    Preset {
192        tag: "nl-NL", decimal: ",", big: ".", min_grouping: 1,
193        currency: "€", suffix: false, spacing: " ", percent: "%",
194        months_short: ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"],
195        months_long: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"],
196        days_short: ["zo", "ma", "di", "wo", "do", "vr", "za"],
197        days_long: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"],
198        date: "%-d %b %Y", month: "%b %Y",
199    },
200    Preset {
201        tag: "nl-BE", decimal: ",", big: ".", min_grouping: 1,
202        currency: "€", suffix: false, spacing: " ", percent: "%",
203        months_short: ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"],
204        months_long: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"],
205        days_short: ["zo", "ma", "di", "wo", "do", "vr", "za"],
206        days_long: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"],
207        date: "%-d %b %Y", month: "%b %Y",
208    },
209    Preset {
210        tag: "pt-PT", decimal: ",", big: " ", min_grouping: 2,
211        currency: "€", suffix: true, spacing: " ", percent: "%",
212        months_short: ["jan.", "fev.", "mar.", "abr.", "mai.", "jun.", "jul.", "ago.", "set.", "out.", "nov.", "dez."],
213        months_long: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
214        days_short: ["domingo", "segunda", "terça", "quarta", "quinta", "sexta", "sábado"],
215        days_long: ["domingo", "segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado"],
216        date: "%-d/%-m/%Y", month: "%b %Y",
217    },
218    Preset {
219        tag: "pt-BR", decimal: ",", big: ".", min_grouping: 1,
220        currency: "R$", suffix: false, spacing: " ", percent: "%",
221        months_short: ["jan.", "fev.", "mar.", "abr.", "mai.", "jun.", "jul.", "ago.", "set.", "out.", "nov.", "dez."],
222        months_long: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
223        days_short: ["dom.", "seg.", "ter.", "qua.", "qui.", "sex.", "sáb."],
224        days_long: ["domingo", "segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado"],
225        date: "%-d de %b de %Y", month: "%b de %Y",
226    },
227    Preset {
228        tag: "pl-PL", decimal: ",", big: " ", min_grouping: 2,
229        currency: "zł", suffix: true, spacing: " ", percent: "%",
230        months_short: ["sty", "lut", "mar", "kwi", "maj", "cze", "lip", "sie", "wrz", "paź", "lis", "gru"],
231        months_long: ["stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca", "lipca", "sierpnia", "września", "października", "listopada", "grudnia"],
232        days_short: ["niedz.", "pon.", "wt.", "śr.", "czw.", "pt.", "sob."],
233        days_long: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"],
234        date: "%-d %b %Y", month: "%b %Y",
235    },
236    Preset {
237        tag: "sv-SE", decimal: ",", big: " ", min_grouping: 1,
238        currency: "kr", suffix: true, spacing: " ", percent: " %",
239        months_short: ["jan.", "feb.", "mars", "apr.", "maj", "juni", "juli", "aug.", "sep.", "okt.", "nov.", "dec."],
240        months_long: ["januari", "februari", "mars", "april", "maj", "juni", "juli", "augusti", "september", "oktober", "november", "december"],
241        days_short: ["sön", "mån", "tis", "ons", "tors", "fre", "lör"],
242        days_long: ["söndag", "måndag", "tisdag", "onsdag", "torsdag", "fredag", "lördag"],
243        date: "%-d %b %Y", month: "%b %Y",
244    },
245    Preset {
246        tag: "da-DK", decimal: ",", big: ".", min_grouping: 1,
247        currency: "kr.", suffix: true, spacing: " ", percent: " %",
248        months_short: ["jan.", "feb.", "mar.", "apr.", "maj", "jun.", "jul.", "aug.", "sep.", "okt.", "nov.", "dec."],
249        months_long: ["januar", "februar", "marts", "april", "maj", "juni", "juli", "august", "september", "oktober", "november", "december"],
250        days_short: ["søn.", "man.", "tirs.", "ons.", "tors.", "fre.", "lør."],
251        days_long: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"],
252        date: "%-d. %b %Y", month: "%b %Y",
253    },
254    Preset {
255        tag: "nb-NO", decimal: ",", big: " ", min_grouping: 1,
256        currency: "kr", suffix: true, spacing: " ", percent: " %",
257        months_short: ["jan.", "feb.", "mars", "apr.", "mai", "juni", "juli", "aug.", "sep.", "okt.", "nov.", "des."],
258        months_long: ["januar", "februar", "mars", "april", "mai", "juni", "juli", "august", "september", "oktober", "november", "desember"],
259        days_short: ["søn.", "man.", "tir.", "ons.", "tor.", "fre.", "lør."],
260        days_long: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"],
261        date: "%-d. %b %Y", month: "%b %Y",
262    },
263    Preset {
264        tag: "fi-FI", decimal: ",", big: " ", min_grouping: 1,
265        currency: "€", suffix: true, spacing: " ", percent: " %",
266        months_short: ["tammi", "helmi", "maalis", "huhti", "touko", "kesä", "heinä", "elo", "syys", "loka", "marras", "joulu"],
267        months_long: ["tammikuuta", "helmikuuta", "maaliskuuta", "huhtikuuta", "toukokuuta", "kesäkuuta", "heinäkuuta", "elokuuta", "syyskuuta", "lokakuuta", "marraskuuta", "joulukuuta"],
268        days_short: ["su", "ma", "ti", "ke", "to", "pe", "la"],
269        days_long: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"],
270        date: "%-d.%-m.%Y", month: "%b %Y",
271    },
272    Preset {
273        tag: "cs-CZ", decimal: ",", big: " ", min_grouping: 1,
274        currency: "Kč", suffix: true, spacing: " ", percent: " %",
275        months_short: ["led", "úno", "bře", "dub", "kvě", "čvn", "čvc", "srp", "zář", "říj", "lis", "pro"],
276        months_long: ["ledna", "února", "března", "dubna", "května", "června", "července", "srpna", "září", "října", "listopadu", "prosince"],
277        days_short: ["ne", "po", "út", "st", "čt", "pá", "so"],
278        days_long: ["neděle", "pondělí", "úterý", "středa", "čtvrtek", "pátek", "sobota"],
279        date: "%-d. %-m. %Y", month: "%b %Y",
280    },
281];
282
283fn strings<const N: usize>(names: [&str; N]) -> [String; N] {
284    names.map(str::to_string)
285}
286
287const EN_MONTHS_SHORT: [&str; 12] = [
288    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
289];
290const EN_MONTHS_LONG: [&str; 12] = [
291    "January",
292    "February",
293    "March",
294    "April",
295    "May",
296    "June",
297    "July",
298    "August",
299    "September",
300    "October",
301    "November",
302    "December",
303];
304const EN_DAYS_SHORT: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
305const EN_DAYS_LONG: [&str; 7] = [
306    "Sunday",
307    "Monday",
308    "Tuesday",
309    "Wednesday",
310    "Thursday",
311    "Friday",
312    "Saturday",
313];
314
315impl Locale {
316    /// English (United States): `1,234.5`, `$1,234.50`, `50%`, `Oct 15, 2026`.
317    pub fn en_us() -> Self {
318        Locale {
319            tag: "en-US".into(),
320            decimal_mark: ".".into(),
321            big_mark: ",".into(),
322            min_grouping_digits: 1,
323            currency_symbol: "$".into(),
324            currency_position: CurrencyPosition::Prefix,
325            currency_spacing: String::new(),
326            percent_suffix: "%".into(),
327            months_short: strings(EN_MONTHS_SHORT),
328            months_long: strings(EN_MONTHS_LONG),
329            days_short: strings(EN_DAYS_SHORT),
330            days_long: strings(EN_DAYS_LONG),
331            date_format: "%b %-d, %Y".into(),
332            month_format: "%b %Y".into(),
333            time_format: "%H:%M".into(),
334        }
335    }
336
337    /// English (United Kingdom): `1,234.5`, `£1,234.50`, `50%`, `15 Oct 2026`.
338    pub fn en_gb() -> Self {
339        Locale {
340            tag: "en-GB".into(),
341            currency_symbol: "£".into(),
342            date_format: "%-d %b %Y".into(),
343            ..Self::en_us()
344        }
345    }
346
347    /// German (Germany): `1.234,5`, `1.234,50 €`, `50 %`, `15. Okt. 2026`.
348    pub fn de_de() -> Self {
349        Locale {
350            tag: "de-DE".into(),
351            decimal_mark: ",".into(),
352            big_mark: ".".into(),
353            min_grouping_digits: 1,
354            currency_symbol: "€".into(),
355            currency_position: CurrencyPosition::Suffix,
356            currency_spacing: " ".into(),
357            percent_suffix: " %".into(),
358            months_short: strings([
359                "Jan.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.",
360                "Nov.", "Dez.",
361            ]),
362            months_long: strings([
363                "Januar",
364                "Februar",
365                "März",
366                "April",
367                "Mai",
368                "Juni",
369                "Juli",
370                "August",
371                "September",
372                "Oktober",
373                "November",
374                "Dezember",
375            ]),
376            days_short: strings(["So.", "Mo.", "Di.", "Mi.", "Do.", "Fr.", "Sa."]),
377            days_long: strings([
378                "Sonntag",
379                "Montag",
380                "Dienstag",
381                "Mittwoch",
382                "Donnerstag",
383                "Freitag",
384                "Samstag",
385            ]),
386            date_format: "%-d. %b %Y".into(),
387            month_format: "%b %Y".into(),
388            time_format: "%H:%M".into(),
389        }
390    }
391
392    /// French (France): `1 234,5`, `1 234,50 €`, `50 %`, `15 oct. 2026`.
393    /// The thousands mark is a plain space (CLDR uses a narrow no-break space,
394    /// which many fonts lack); set [`big_mark`](Self::big_mark) to override.
395    pub fn fr_fr() -> Self {
396        Locale {
397            tag: "fr-FR".into(),
398            decimal_mark: ",".into(),
399            big_mark: " ".into(),
400            min_grouping_digits: 1,
401            currency_symbol: "€".into(),
402            currency_position: CurrencyPosition::Suffix,
403            currency_spacing: " ".into(),
404            percent_suffix: " %".into(),
405            months_short: strings([
406                "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.",
407                "nov.", "déc.",
408            ]),
409            months_long: strings([
410                "janvier",
411                "février",
412                "mars",
413                "avril",
414                "mai",
415                "juin",
416                "juillet",
417                "août",
418                "septembre",
419                "octobre",
420                "novembre",
421                "décembre",
422            ]),
423            days_short: strings(["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."]),
424            days_long: strings([
425                "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi",
426            ]),
427            date_format: "%-d %b %Y".into(),
428            month_format: "%b %Y".into(),
429            time_format: "%H:%M".into(),
430        }
431    }
432
433    /// The preset for a BCP-47-ish tag, if one matches: case-insensitive,
434    /// `-` or `_` separated, POSIX suffixes (`.UTF-8`, `@euro`) ignored.
435    /// A CLDR preset for the exact language and region first (`de-AT`,
436    /// `de-CH`, `fr-CA`, `it-IT`, `es-MX`, `pt-BR`, … — [`preset_tags`](Self::preset_tags)),
437    /// then the language's main locale (`it` → it-IT, `pt` → pt-BR, `nb`/`no`
438    /// → nb-NO), then `de*` → [`de_de`](Self::de_de), `fr*` →
439    /// [`fr_fr`](Self::fr_fr), `en-GB` / `en-UK` → [`en_gb`](Self::en_gb),
440    /// other `en*` and `C` / `POSIX` → [`en_us`](Self::en_us).
441    pub fn try_from_tag(tag: &str) -> Option<Self> {
442        let t = tag
443            .trim()
444            .split(['.', '@'])
445            .next()
446            .unwrap_or("")
447            .replace('_', "-")
448            .to_ascii_lowercase();
449        let mut parts = t.split('-');
450        let lang = parts.next().unwrap_or("");
451        // Skip a script subtag (e.g. "Latn") to find the region.
452        let region = parts.find(|p| p.len() != 4).unwrap_or("");
453        // a CLDR preset for exactly this language and region (de-AT, pt-BR, …)
454        let exact = PRESETS.iter().find(|p| {
455            let (l, r) = p.tag.split_once('-').unwrap_or((p.tag, ""));
456            l.eq_ignore_ascii_case(lang) && r.eq_ignore_ascii_case(region)
457        });
458        if let Some(p) = exact {
459            return Some(Self::from_preset(p));
460        }
461        // else the language's main locale (CLDR's default region)
462        let main = match lang {
463            "it" => "it-IT",
464            "es" => "es-ES",
465            "nl" => "nl-NL",
466            "pt" => "pt-BR",
467            "pl" => "pl-PL",
468            "sv" => "sv-SE",
469            "da" => "da-DK",
470            "nb" | "no" | "nn" => "nb-NO",
471            "fi" => "fi-FI",
472            "cs" => "cs-CZ",
473            _ => "",
474        };
475        if let Some(p) = PRESETS.iter().find(|p| p.tag == main) {
476            return Some(Self::from_preset(p));
477        }
478        match (lang, region) {
479            ("de", _) => Some(Self::de_de()),
480            ("fr", _) => Some(Self::fr_fr()),
481            ("en", "gb" | "uk") => Some(Self::en_gb()),
482            ("en", _) | ("c", "") | ("posix", "") => Some(Self::en_us()),
483            _ => None,
484        }
485    }
486
487    /// Every tag [`try_from_tag`](Self::try_from_tag) has a preset for.
488    pub fn preset_tags() -> Vec<&'static str> {
489        ["en-US", "en-GB", "de-DE", "fr-FR"]
490            .into_iter()
491            .chain(PRESETS.iter().map(|p| p.tag))
492            .collect()
493    }
494
495    fn from_preset(p: &Preset) -> Self {
496        Locale {
497            tag: p.tag.into(),
498            decimal_mark: p.decimal.into(),
499            big_mark: p.big.into(),
500            min_grouping_digits: p.min_grouping,
501            currency_symbol: p.currency.into(),
502            currency_position: if p.suffix {
503                CurrencyPosition::Suffix
504            } else {
505                CurrencyPosition::Prefix
506            },
507            currency_spacing: p.spacing.into(),
508            percent_suffix: p.percent.into(),
509            months_short: strings(p.months_short),
510            months_long: strings(p.months_long),
511            days_short: strings(p.days_short),
512            days_long: strings(p.days_long),
513            date_format: p.date.into(),
514            month_format: p.month.into(),
515            time_format: "%H:%M".into(),
516        }
517    }
518
519    /// Like [`try_from_tag`](Self::try_from_tag), falling back to
520    /// [`en_us`](Self::en_us) for unknown tags.
521    ///
522    /// ```
523    /// use ggplot_rs::locale::Locale;
524    /// assert_eq!(Locale::from_tag("de-DE").tag, "de-DE");
525    /// assert_eq!(Locale::from_tag("fr_FR.UTF-8").tag, "fr-FR");
526    /// assert_eq!(Locale::from_tag("en-GB").tag, "en-GB");
527    /// assert_eq!(Locale::from_tag("xx-YY").tag, "en-US");
528    /// ```
529    pub fn from_tag(tag: &str) -> Self {
530        Self::try_from_tag(tag).unwrap_or_else(Self::en_us)
531    }
532
533    /// Replace the decimal mark.
534    pub fn with_decimal_mark(mut self, mark: &str) -> Self {
535        self.decimal_mark = mark.to_string();
536        self
537    }
538
539    /// Replace the thousands mark (`""` disables grouping).
540    pub fn with_big_mark(mut self, mark: &str) -> Self {
541        self.big_mark = mark.to_string();
542        self
543    }
544
545    /// Replace the minimum grouping digits (see
546    /// [`min_grouping_digits`](Self::min_grouping_digits)).
547    pub fn with_min_grouping_digits(mut self, digits: usize) -> Self {
548        self.min_grouping_digits = digits;
549        self
550    }
551
552    /// Use another currency symbol, placed by this locale's convention:
553    /// `Locale::de_de().with_currency("CHF")` formats `1.234,50 CHF`.
554    pub fn with_currency(mut self, symbol: &str) -> Self {
555        self.currency_symbol = symbol.to_string();
556        self
557    }
558
559    /// `(prefix, suffix)` that place `symbol` by this locale's convention:
560    /// `("$", "")` for en-US, `("", " €")` for de-DE.
561    pub fn currency_affixes(&self, symbol: &str) -> (String, String) {
562        match self.currency_position {
563            CurrencyPosition::Prefix => {
564                (format!("{symbol}{}", self.currency_spacing), String::new())
565            }
566            CurrencyPosition::Suffix => {
567                (String::new(), format!("{}{symbol}", self.currency_spacing))
568            }
569        }
570    }
571
572    /// Re-render a number formatted the default way (`.` decimal mark, `,` or
573    /// no thousands grouping, optional leading `-`) with this locale's marks:
574    /// `"-1234.5"` / `"-1,234.5"` → `"-1.234,5"` in de-DE. Anything that is not
575    /// such a number (`NaN`, `inf`, text) is returned unchanged.
576    pub fn localize_number(&self, s: &str) -> String {
577        localize_number(
578            s,
579            &self.decimal_mark,
580            &self.big_mark,
581            self.min_grouping_digits,
582        )
583    }
584
585    /// Inverse of [`localize_number`](Self::localize_number) for parsing a
586    /// label back to a number: strips thousands marks and restores `.`.
587    pub fn parse_number(&self, s: &str) -> Option<f64> {
588        let mut t = s.trim().to_string();
589        if !self.big_mark.is_empty() {
590            t = t.replace(&self.big_mark, "");
591        }
592        if self.decimal_mark != "." {
593            t = t.replace(&self.decimal_mark, ".");
594        }
595        t.parse().ok()
596    }
597
598    /// Format a break value like the default axis labels (integers verbatim,
599    /// otherwise up to two decimals, trailing zeros trimmed) with this
600    /// locale's marks: `1234.5` → `"1.234,5"` in de-DE.
601    pub fn format_number(&self, v: f64) -> String {
602        crate::scale::util::format_number_locale(v, self)
603    }
604
605    /// Format epoch seconds (UTC) with a strftime-style format, using this
606    /// locale's month and weekday names. Supported: `%Y %y %m %-m %b %B %d
607    /// %-d %e %a %A %H %M %S %%`.
608    pub fn strftime(&self, epoch_secs: i64, fmt: &str) -> String {
609        crate::scale::datetime::strftime_locale(epoch_secs as f64, fmt, Some(self))
610    }
611
612    /// Format epoch seconds (UTC) as this locale's date ([`date_format`](Self::date_format)),
613    /// plus [`time_format`](Self::time_format) when not at midnight.
614    pub fn format_datetime(&self, epoch_secs: i64) -> String {
615        let fmt = if epoch_secs.rem_euclid(86_400) == 0 {
616            self.date_format.clone()
617        } else {
618            format!("{} {}", self.date_format, self.time_format)
619        };
620        self.strftime(epoch_secs, &fmt)
621    }
622}
623
624impl Default for Locale {
625    /// [`Locale::en_us`].
626    fn default() -> Self {
627        Self::en_us()
628    }
629}
630
631impl std::str::FromStr for Locale {
632    type Err = std::convert::Infallible;
633    /// [`Locale::from_tag`] (never fails; unknown tags give en-US).
634    fn from_str(s: &str) -> Result<Self, Self::Err> {
635        Ok(Self::from_tag(s))
636    }
637}
638
639/// Re-render a default-formatted number (`-1,234.5` or `-1234.5`) with the
640/// given marks; see [`Locale::localize_number`].
641pub(crate) fn localize_number(
642    s: &str,
643    decimal_mark: &str,
644    big_mark: &str,
645    min_grouping_digits: usize,
646) -> String {
647    let (sign, rest) = match s.strip_prefix('-') {
648        Some(r) => ("-", r),
649        None => ("", s),
650    };
651    let (int_part, dec_part) = match rest.split_once('.') {
652        Some((i, d)) => (i, Some(d)),
653        None => (rest, None),
654    };
655    let digits: String = int_part.chars().filter(|&c| c != ',').collect();
656    let is_number = !digits.is_empty()
657        && digits.chars().all(|c| c.is_ascii_digit())
658        && int_part.chars().all(|c| c.is_ascii_digit() || c == ',')
659        && dec_part.is_none_or(|d| d.chars().all(|c| c.is_ascii_digit()));
660    if !is_number {
661        return s.to_string();
662    }
663    let n = digits.len();
664    let mut out = String::with_capacity(s.len() + n / 3 * big_mark.len());
665    out.push_str(sign);
666    let group = !big_mark.is_empty() && n >= 3 + min_grouping_digits.max(1);
667    for (i, ch) in digits.chars().enumerate() {
668        if group && i > 0 && (n - i).is_multiple_of(3) {
669            out.push_str(big_mark);
670        }
671        out.push(ch);
672    }
673    if let Some(d) = dec_part {
674        out.push_str(decimal_mark);
675        out.push_str(d);
676    }
677    out
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683
684    #[test]
685    fn localize_regroups_and_swaps_marks() {
686        let de = Locale::de_de();
687        assert_eq!(de.localize_number("1234.5"), "1.234,5");
688        assert_eq!(de.localize_number("-1,234,567.25"), "-1.234.567,25");
689        assert_eq!(de.localize_number("999"), "999");
690        assert_eq!(de.localize_number("0.5"), "0,5");
691        assert_eq!(de.localize_number("NaN"), "NaN");
692        assert_eq!(de.localize_number("-inf"), "-inf");
693        assert_eq!(de.localize_number(""), "");
694        let fr = Locale::fr_fr();
695        assert_eq!(fr.localize_number("1234567.5"), "1 234 567,5");
696        let no_group = Locale::de_de().with_big_mark("");
697        assert_eq!(no_group.localize_number("1,234.5"), "1234,5");
698        let min2 = Locale::de_de().with_min_grouping_digits(2);
699        assert_eq!(min2.localize_number("2020"), "2020");
700        assert_eq!(min2.localize_number("20200"), "20.200");
701    }
702
703    #[test]
704    fn parse_number_inverts_localize() {
705        let de = Locale::de_de();
706        assert_eq!(de.parse_number("1.234,5"), Some(1234.5));
707        assert_eq!(de.parse_number("-0,25"), Some(-0.25));
708        assert_eq!(Locale::fr_fr().parse_number("1 000"), Some(1000.0));
709        assert_eq!(Locale::en_us().parse_number("1,000.5"), Some(1000.5));
710    }
711
712    #[test]
713    fn tags_resolve_to_presets() {
714        for (tag, want) in [
715            ("de-DE", "de-DE"),
716            ("de", "de-DE"),
717            ("DE_at", "de-AT"),
718            ("de-LU", "de-DE"),
719            ("de_DE.UTF-8", "de-DE"),
720            ("de_DE@euro", "de-DE"),
721            ("fr-FR", "fr-FR"),
722            ("fr-CA", "fr-CA"),
723            ("fr-LU", "fr-FR"),
724            ("it", "it-IT"),
725            ("pt", "pt-BR"),
726            ("no", "nb-NO"),
727            ("es", "es-ES"),
728            ("es-AR", "es-ES"),
729            ("nl", "nl-NL"),
730            ("pl", "pl-PL"),
731            ("sv-FI", "sv-SE"),
732            ("da", "da-DK"),
733            ("nb", "nb-NO"),
734            ("nn", "nb-NO"),
735            ("fi", "fi-FI"),
736            ("cs", "cs-CZ"),
737            ("pt-PT", "pt-PT"),
738            ("it-CH", "it-CH"),
739            ("en-GB", "en-GB"),
740            ("en_gb", "en-GB"),
741            ("en-Latn-GB", "en-GB"),
742            ("en-US", "en-US"),
743            ("en", "en-US"),
744            ("C", "en-US"),
745            ("", "en-US"),
746            ("ja-JP", "en-US"),
747        ] {
748            assert_eq!(Locale::from_tag(tag).tag, want, "{tag:?}");
749        }
750        assert!(Locale::try_from_tag("ja-JP").is_none());
751        assert!(Locale::try_from_tag("").is_none());
752        assert_eq!("de-DE".parse::<Locale>().unwrap(), Locale::de_de());
753        assert_eq!(Locale::default(), Locale::en_us());
754    }
755
756    #[test]
757    fn currency_affixes_follow_placement() {
758        assert_eq!(
759            Locale::en_us().currency_affixes("$"),
760            ("$".into(), String::new())
761        );
762        assert_eq!(
763            Locale::de_de().currency_affixes("€"),
764            (String::new(), " €".into())
765        );
766        assert_eq!(
767            Locale::en_gb().currency_affixes("£"),
768            ("£".into(), String::new())
769        );
770    }
771
772    #[test]
773    fn dates_per_locale() {
774        let t = 1_792_022_400; // 2026-10-15 00:00 UTC (Thursday)
775        assert_eq!(Locale::de_de().format_datetime(t), "15. Okt. 2026");
776        assert_eq!(Locale::en_us().format_datetime(t), "Oct 15, 2026");
777        assert_eq!(Locale::en_gb().format_datetime(t), "15 Oct 2026");
778        assert_eq!(Locale::fr_fr().format_datetime(t), "15 oct. 2026");
779        assert_eq!(
780            Locale::de_de().format_datetime(t + 9 * 3600 + 30 * 60),
781            "15. Okt. 2026 09:30"
782        );
783        assert_eq!(
784            Locale::de_de().strftime(t, "%A, %-d. %B %Y"),
785            "Donnerstag, 15. Oktober 2026"
786        );
787        assert_eq!(Locale::fr_fr().strftime(t, "%a %-d %B"), "jeu. 15 octobre");
788        assert_eq!(Locale::en_us().strftime(t, "%a %A"), "Thu Thursday");
789        assert_eq!(Locale::de_de().strftime(t - 86_400 * 200, "%B"), "März");
790    }
791}