leptos_use/
use_intl_number_format.rs

1#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports, dead_code))]
2
3use crate::{js, sendwrap_fn, utils::js_value_from_to_string};
4use cfg_if::cfg_if;
5use default_struct_builder::DefaultBuilder;
6use leptos::prelude::*;
7use leptos::reactive::wrappers::read::Signal;
8use std::fmt::Display;
9use wasm_bindgen::{JsCast, JsValue};
10
11/// Reactive [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).
12///
13/// ## Demo
14///
15/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_intl_number_format)
16///
17/// ## Usage
18///
19/// In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
20///
21/// ```
22/// # use leptos::prelude::*;
23/// # use leptos_use::{use_intl_number_format, UseIntlNumberFormatOptions};
24/// #
25/// # #[component]
26/// # fn Demo() -> impl IntoView {
27/// let (number, set_number) = signal(3500);
28///
29/// let number_format = use_intl_number_format(UseIntlNumberFormatOptions::default());
30///
31/// let formatted = number_format.format::<u16>(number); // "3,500" if in US English locale
32/// #
33/// # view! { }
34/// # }
35/// ```
36///
37/// ## Using locales
38///
39/// This example shows some of the variations in localized number formats. In order to get the format
40/// of the language used in the user interface of your application, make sure to specify that language
41/// (and possibly some fallback languages) using the `locales` argument:
42///
43/// ```
44/// # use leptos::prelude::*;
45/// # use leptos_use::{use_intl_number_format, UseIntlNumberFormatOptions};
46/// #
47/// # #[component]
48/// # fn Demo() -> impl IntoView {
49/// let number = 123456.789_f32;
50///
51/// // German uses comma as decimal separator and period for thousands
52/// let number_format = use_intl_number_format(
53///     UseIntlNumberFormatOptions::default().locale("de-DE"),
54/// );
55/// let formatted = number_format.format::<f32>(number); // 123.456,789
56///
57/// // Arabic in most Arabic speaking countries uses real Arabic digits
58/// let number_format = use_intl_number_format(
59///     UseIntlNumberFormatOptions::default().locale("ar-EG"),
60/// );
61/// let formatted = number_format.format::<f32>(number); // ١٢٣٤٥٦٫٧٨٩
62///
63/// // India uses thousands/lakh/crore separators
64/// let number_format = use_intl_number_format(
65///     UseIntlNumberFormatOptions::default().locale("en-IN"),
66/// );
67/// let formatted = number_format.format::<f32>(number); // 1,23,456.789
68///
69/// // the nu extension key requests a numbering system, e.g. Chinese decimal
70/// let number_format = use_intl_number_format(
71///     UseIntlNumberFormatOptions::default().locale("zh-Hans-CN-u-nu-hanidec"),
72/// );
73/// let formatted = number_format.format::<f32>(number); // 一二三,四五六.七八九
74///
75/// // when requesting a language that may not be supported, such as
76/// // Balinese, include a fallback language, in this case Indonesian
77/// let number_format = use_intl_number_format(
78///     UseIntlNumberFormatOptions::default().locales(vec!["ban".to_string(), "id".to_string()]),
79/// );
80/// let formatted = number_format.format::<f32>(number); // 123.456,789
81///
82/// #
83/// # view! { }
84/// # }
85/// ```
86///
87/// ## Using options
88///
89/// The results can be customized in multiple ways.
90///
91/// ```
92/// # use leptos::prelude::*;
93/// # use leptos_use::{NumberStyle, UnitDisplay, use_intl_number_format, UseIntlNumberFormatOptions};
94/// #
95/// # #[component]
96/// # fn Demo() -> impl IntoView {
97/// let number = 123456.789_f64;
98///
99/// // request a currency format
100/// let number_format = use_intl_number_format(
101///     UseIntlNumberFormatOptions::default()
102///         .locale("de-DE")
103///         .style(NumberStyle::Currency)
104///         .currency("EUR"),
105/// );
106/// let formatted = number_format.format::<f64>(number); // 123.456,79 €
107///
108/// // the Japanese yen doesn't use a minor unit
109/// let number_format = use_intl_number_format(
110///     UseIntlNumberFormatOptions::default()
111///         .locale("ja-JP")
112///         .style(NumberStyle::Currency)
113///         .currency("JPY"),
114/// );
115/// let formatted = number_format.format::<f64>(number); // ¥123,457
116///
117/// // limit to three significant digits
118/// let number_format = use_intl_number_format(
119///     UseIntlNumberFormatOptions::default()
120///         .locale("en-IN")
121///         .maximum_significant_digits(3),
122/// );
123/// let formatted = number_format.format::<f64>(number); // 1,23,000
124///
125/// // Formatting with units
126/// let number_format = use_intl_number_format(
127///     UseIntlNumberFormatOptions::default()
128///         .locale("pt-PT")
129///         .style(NumberStyle::Unit)
130///         .unit("kilometer-per-hour"),
131/// );
132/// let formatted = number_format.format::<i32>(50); // 50 km/h
133///
134/// let number_format = use_intl_number_format(
135///     UseIntlNumberFormatOptions::default()
136///         .locale("en-GB")
137///         .style(NumberStyle::Unit)
138///         .unit("liter")
139///         .unit_display(UnitDisplay::Long),
140/// );
141/// let formatted = number_format.format::<i32>(16); // 16 litres
142/// #
143/// # view! { }
144/// # }
145/// ```
146///
147/// For an exhaustive list of options see [`UseIntlNumberFormatOptions`](https://docs.rs/leptos_use/latest/leptos_use/struct.UseIntlNumberFormatOptions.html).
148///
149/// ## Formatting ranges
150///
151/// Apart from the `format` method, the `format_range` method can be used to format a range of numbers.
152/// Please see [`UseIntlNumberFormatReturn::format_range`](https://docs.rs/leptos_use/latest/leptos_use/struct.UseIntlNumberFormatReturn.html#method.format_range)
153/// for details.
154///
155/// ## Server-Side Rendering
156///
157/// > Make sure you follow the [instructions in Server-Side Rendering](https://leptos-use.rs/server_side_rendering.html).
158///
159/// Since `Intl.NumberFormat` is a JavaScript API it is not available on the server. That's why
160/// it falls back to a simple call to `format!()` on the server.
161pub fn use_intl_number_format(options: UseIntlNumberFormatOptions) -> UseIntlNumberFormatReturn {
162    cfg_if! { if #[cfg(feature = "ssr")] {
163        UseIntlNumberFormatReturn
164    } else {
165        let number_format = js_sys::Intl::NumberFormat::new(
166            &js_sys::Array::from_iter(options.locales.iter().map(JsValue::from)),
167            &js_sys::Object::from(options),
168        );
169
170        UseIntlNumberFormatReturn {
171            js_intl_number_format: number_format,
172        }
173    }}
174}
175
176#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
177pub enum CompactDisplay {
178    #[default]
179    Short,
180    Long,
181}
182
183impl Display for CompactDisplay {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        match self {
186            Self::Short => write!(f, "short"),
187            Self::Long => write!(f, "long"),
188        }
189    }
190}
191
192js_value_from_to_string!(CompactDisplay);
193
194/// How to display the currency in currency formatting.
195#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
196pub enum CurrencyDisplay {
197    /// use a localized currency symbol such as €.
198    #[default]
199    Symbol,
200    /// use a narrow format symbol ("$100" rather than "US$100").
201    NarrowSymbol,
202    /// use the ISO currency code.
203    Code,
204    /// use a localized currency name such as "dollar".
205    Name,
206}
207
208impl Display for CurrencyDisplay {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        match self {
211            Self::Symbol => write!(f, "symbol"),
212            Self::NarrowSymbol => write!(f, "narrowSymbol"),
213            Self::Code => write!(f, "code"),
214            Self::Name => write!(f, "name"),
215        }
216    }
217}
218
219js_value_from_to_string!(CurrencyDisplay);
220
221#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
222pub enum CurrencySign {
223    #[default]
224    Standard,
225    Accounting,
226}
227
228impl Display for CurrencySign {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        match self {
231            Self::Standard => write!(f, "standard"),
232            Self::Accounting => write!(f, "accounting"),
233        }
234    }
235}
236
237js_value_from_to_string!(CurrencySign);
238
239#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
240pub enum LocaleMatcher {
241    #[default]
242    BestFit,
243    Lookup,
244}
245
246impl Display for LocaleMatcher {
247    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248        match self {
249            Self::BestFit => write!(f, "best fit"),
250            Self::Lookup => write!(f, "lookup"),
251        }
252    }
253}
254
255js_value_from_to_string!(LocaleMatcher);
256
257/// The formatting that should be displayed for the number.
258#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
259pub enum Notation {
260    /// plain number formatting.
261    #[default]
262    Standard,
263    /// order-of-magnitude for formatted number.
264    Scientific,
265    /// exponent of ten when divisible by three.
266    Engineering,
267    /// string representing exponent
268    Compact,
269}
270
271impl Display for Notation {
272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        match self {
274            Self::Standard => write!(f, "standard"),
275            Self::Scientific => write!(f, "scientific"),
276            Self::Engineering => write!(f, "engineering"),
277            Self::Compact => write!(f, "compact"),
278        }
279    }
280}
281
282js_value_from_to_string!(Notation);
283
284/// When to display the sign for the number.
285#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
286pub enum SignDisplay {
287    /// sign display for negative numbers only, including negative zero.
288    #[default]
289    Auto,
290    /// always display the sign.
291    Always,
292    /// sign display for positive and negative numbers, but not zero.
293    ExceptZero,
294    /// sign display for negative numbers only, excluding negative zero. Experimental.
295    Negative,
296    /// never display sign.
297    Never,
298}
299
300impl Display for SignDisplay {
301    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302        match self {
303            Self::Auto => write!(f, "auto"),
304            Self::Always => write!(f, "always"),
305            Self::ExceptZero => write!(f, "exceptZero"),
306            Self::Negative => write!(f, "negative"),
307            Self::Never => write!(f, "never"),
308        }
309    }
310}
311
312js_value_from_to_string!(SignDisplay);
313
314#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
315pub enum NumberStyle {
316    #[default]
317    Decimal,
318    Currency,
319    Percent,
320    Unit,
321}
322
323impl Display for NumberStyle {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        match self {
326            Self::Decimal => write!(f, "decimal"),
327            Self::Currency => write!(f, "currency"),
328            Self::Percent => write!(f, "percent"),
329            Self::Unit => write!(f, "unit"),
330        }
331    }
332}
333
334js_value_from_to_string!(NumberStyle);
335
336#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
337pub enum UnitDisplay {
338    /// e.g., `16 litres`
339    Long,
340    /// e.g., `16 l`
341    #[default]
342    Short,
343    /// e.g., `16l`
344    Narrow,
345}
346
347impl Display for UnitDisplay {
348    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349        match self {
350            Self::Long => write!(f, "long"),
351            Self::Short => write!(f, "short"),
352            Self::Narrow => write!(f, "narrow"),
353        }
354    }
355}
356
357js_value_from_to_string!(UnitDisplay);
358
359#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
360pub enum NumberGrouping {
361    /// display grouping separators even if the locale prefers otherwise.
362    Always,
363    /// display grouping separators based on the locale preference, which may also be dependent on the currency.
364    #[default]
365    Auto,
366    /// do not display grouping separators.
367    None,
368    /// display grouping separators when there are at least 2 digits in a group.
369    Min2,
370}
371
372impl Display for NumberGrouping {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        match self {
375            Self::Always => write!(f, "always"),
376            Self::Auto => write!(f, "auto"),
377            Self::None => write!(f, "none"),
378            Self::Min2 => write!(f, "min2"),
379        }
380    }
381}
382
383impl From<NumberGrouping> for JsValue {
384    fn from(value: NumberGrouping) -> Self {
385        match value {
386            NumberGrouping::None => JsValue::from(false),
387            _ => JsValue::from(&value.to_string()),
388        }
389    }
390}
391
392#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
393pub enum RoundingMode {
394    /// round toward +∞. Positive values round up. Negative values round "more positive".
395    Ceil,
396    /// round toward -∞. Positive values round down. Negative values round "more negative".
397    Floor,
398    /// round away from 0. The _magnitude_ of the value is always increased by rounding. Positive values round up. Negative values round "more negative".
399    Expand,
400    /// round toward 0. This _magnitude_ of the value is always reduced by rounding. Positive values round down. Negative values round "less negative".
401    Trunc,
402    /// ties toward +∞. Values above the half-increment round like `Ceil` (towards +∞), and below like `Floor` (towards -∞). On the half-increment, values round like `Ceil`.
403    HalfCeil,
404    /// ties toward -∞. Values above the half-increment round like `Ceil` (towards +∞), and below like `Floor` (towards -∞). On the half-increment, values round like `Floor`.
405    HalfFloor,
406    /// ties away from 0. Values above the half-increment round like `Expand` (away from zero), and below like `Trunc` (towards 0). On the half-increment, values round like `Expand`.
407    #[default]
408    HalfExpand,
409    /// ties toward 0. Values above the half-increment round like `Expand` (away from zero), and below like `Trunc` (towards 0). On the half-increment, values round like `Trunc`.
410    HalfTrunc,
411    /// ties towards the nearest even integer. Values above the half-increment round like `Expand` (away from zero), and below like `Trunc` (towards 0). On the half-increment values round towards the nearest even digit.
412    HalfEven,
413}
414
415impl Display for RoundingMode {
416    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417        match self {
418            Self::Ceil => write!(f, "ceil"),
419            Self::Floor => write!(f, "floor"),
420            Self::Expand => write!(f, "expand"),
421            Self::Trunc => write!(f, "trunc"),
422            Self::HalfCeil => write!(f, "halfCeil"),
423            Self::HalfFloor => write!(f, "halfFloor"),
424            Self::HalfExpand => write!(f, "halfExpand"),
425            Self::HalfTrunc => write!(f, "halfTrunc"),
426            Self::HalfEven => write!(f, "halfEven"),
427        }
428    }
429}
430
431js_value_from_to_string!(RoundingMode);
432
433#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
434pub enum RoundingPriority {
435    /// the result from the significant digits property is used.
436    #[default]
437    Auto,
438    /// the result from the property that results in more precision is used.
439    MorePrecision,
440    /// the result from the property that results in less precision is used.
441    LessPrecision,
442}
443
444impl Display for RoundingPriority {
445    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
446        match self {
447            Self::Auto => write!(f, "auto"),
448            Self::MorePrecision => write!(f, "morePrecision"),
449            Self::LessPrecision => write!(f, "lessPrecision"),
450        }
451    }
452}
453
454js_value_from_to_string!(RoundingPriority);
455
456#[derive(Default, Copy, Clone, PartialEq, Eq, Hash, Debug)]
457pub enum TrailingZeroDisplay {
458    /// keep trailing zeros according to `minimum_fraction_digits` and `minimum_significant_digits`.
459    #[default]
460    Auto,
461    /// remove the fraction digits _if_ they are all zero. This is the same as `Auto` if any of the fraction digits is non-zero.
462    StripIfInteger,
463}
464
465impl Display for TrailingZeroDisplay {
466    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
467        match self {
468            Self::Auto => write!(f, "auto"),
469            Self::StripIfInteger => write!(f, "stripIfInteger"),
470        }
471    }
472}
473
474js_value_from_to_string!(TrailingZeroDisplay);
475
476/// Options for [`use_intl_number_format`].
477#[derive(DefaultBuilder)]
478pub struct UseIntlNumberFormatOptions {
479    /// A vec of strings, each with a BCP 47 language tag. Please refer to the
480    /// [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters)
481    /// for more info.
482    locales: Vec<String>,
483
484    /// Only used when [`UseIntlNumberFormatOptions::notation`] is `Compact`. Takes either `Short` (default) or `Long`.
485    compact_display: CompactDisplay,
486
487    /// The currency to use in currency formatting.
488    /// Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro,
489    /// or "CNY" for the Chinese RMB — see the [Current currency & funds code list](https://www.six-group.com/en/products-services/financial-information/data-standards.html#scrollTo=currency-codes).
490    /// There is no default value; if the style is `Currency`, the currency property must be provided.
491    #[builder(into)]
492    currency: Option<String>,
493
494    /// How to display the currency in currency formatting. The default is `Symbol`.
495    ///
496    /// - `Symbol`: use a localized currency symbol such as €.
497    /// - `NarrowSymbol`: use a narrow format symbol ("$100" rather than "US$100").
498    /// - `Code`: use the ISO currency code.
499    /// - `Name`: use a localized currency name such as `"dollar"`.
500    currency_display: CurrencyDisplay,
501
502    /// In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign.
503    /// You can enable this formatting by setting this option to `Accounting`. The default value is `Standard`.
504    currency_sign: CurrencySign,
505
506    /// The locale matching algorithm to use. Possible values are `Lookup` and `BestFit`; the default is `"BestFit"`.
507    /// For information about this option, see the [Intl page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
508    locale_matcher: LocaleMatcher,
509
510    /// The formatting that should be displayed for the number. The default is `"standard"`.
511    ///
512    /// - `Standard`: plain number formatting.
513    /// - `Scientific`: order-of-magnitude for formatted number.
514    /// - `Engineering`: exponent of ten when divisible by three.
515    /// - `Compact`: string representing exponent; See [`UseIntlNumberFormatOptions::compact_display`].
516    notation: Notation,
517
518    /// Numbering System. Possible values include: `"arab"`, `"arabext"`, `"bali"`, `"beng"`, `"deva"`, `"fullwide"`, `"gujr"`, `"guru"`, `"hanidec"`, `"khmr"`, `"knda"`, `"laoo"`, `"latn"`, `"limb"`, `"mlym"`, `"mong"`, `"mymr"`, `"orya"`, `"tamldec"`, `"telu"`, `"thai"`, `"tibt"`.
519    #[builder(into)]
520    numbering_system: Option<String>,
521
522    /// When to display the sign for the number. The default is `Auto`.
523    ///
524    /// - `Auto`: sign display for negative numbers only, including negative zero.
525    /// - `Always`: always display sign.
526    /// - `ExceptZero`: sign display for positive and negative numbers, but not zero.
527    /// - `Negative`: sign display for negative numbers only, excluding negative zero. Experimental
528    /// - `Never`: never display sign.
529    sign_display: SignDisplay,
530
531    /// The formatting style to use. The default is `Decimal`.
532    ///
533    /// - `Decimal` for plain number formatting.
534    /// - `Currency` for currency formatting.
535    /// - `Percent` for percent formatting.
536    /// - `Unit` for unit formatting.
537    style: NumberStyle,
538
539    /// The unit to use in `unit` formatting, Possible values are core unit identifiers,
540    /// defined in [UTS #35, Part 2, Section 6](https://unicode.org/reports/tr35/tr35-general.html#Unit_Elements).
541    /// A [subset](https://tc39.es/ecma402/#table-sanctioned-single-unit-identifiers) of units
542    /// from the [full list](https://github.com/unicode-org/cldr/blob/main/common/validity/unit.xml)
543    /// was selected for use in ECMAScript.
544    /// Pairs of simple units can be concatenated with "-per-" to make a compound unit.
545    /// There is no default value; if the `style` is `Unit`, the `unit` property must be provided.
546    #[builder(into)]
547    unit: Option<String>,
548
549    /// The unit formatting style to use in `unit` formatting. The default is `Short`.
550    ///
551    /// - `Long` (e.g., `16 litres`).
552    /// - `Short` (e.g., `16 l`).
553    /// - `Narrow` (e.g., `16l`).
554    unit_display: UnitDisplay,
555
556    /// Experimental.
557    /// Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.
558    /// The default is `Auto`.
559    ///
560    /// - `Always`: display grouping separators even if the locale prefers otherwise.
561    /// - `Auto`: display grouping separators based on the locale preference, which may also be dependent on the currency.
562    /// - `None`: do not display grouping separators.
563    /// - `Min2`: display grouping separators when there are at least 2 digits in a group.
564    use_grouping: NumberGrouping,
565
566    /// Experimental.
567    /// Options for rounding modes. The default is `HalfExpand`.
568    ///
569    /// - `Ceil`: round toward +∞. Positive values round up. Negative values round "more positive".
570    /// - `Floor` round toward -∞. Positive values round down. Negative values round "more negative".
571    /// - `Expand`: round away from 0. The _magnitude_ of the value is always increased by rounding. Positive values round up. Negative values round "more negative".
572    /// - `Trunc`: round toward 0. This _magnitude_ of the value is always reduced by rounding. Positive values round down. Negative values round "less negative".
573    /// - `HalfCeil`: ties toward +∞. Values above the half-increment round like `Ceil` (towards +∞), and below like `Floor` (towards -∞). On the half-increment, values round like `Ceil`.
574    /// - `HalfFloor`: ties toward -∞. Values above the half-increment round like `Ceil` (towards +∞), and below like `Floor` (towards -∞). On the half-increment, values round like `Floor`.
575    /// - `HalfExpand`: ties away from 0. Values above the half-increment round like `Expand` (away from zero), and below like `Trunc` (towards 0). On the half-increment, values round like `Expand`.
576    /// - `HalfTrunc`: ties toward 0. Values above the half-increment round like `Expand` (away from zero), and below like `Trunc` (towards 0). On the half-increment, values round like `Trunc`.
577    /// - `HalfEven`: ties towards the nearest even integer. Values above the half-increment round like `Expand` (away from zero), and below like `Trunc` (towards 0). On the half-increment values round towards the nearest even digit.
578    ///
579    /// These options reflect the [ICU user guide](https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes.html), where `Expand` and `Trunc` map to ICU "UP" and "DOWN", respectively. The [rounding modes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#rounding_modes) example demonstrates how each mode works.
580    rounding_mode: RoundingMode,
581
582    /// Experimental.
583    /// Specify how rounding conflicts will be resolved if both "FractionDigits" ([`UseIntlNumberFormatOptions::minimum_fraction_digits`]/[`UseIntlNumberFormatOptions::maximum_fraction_digits`]) and "SignificantDigits" ([`UseIntlNumberFormatOptions::minimum_significant_digits`]/[`UseIntlNumberFormatOptions::maximum_significant_digits`]) are specified:
584    ///
585    /// - `Auto`: the result from the significant digits property is used (default).
586    /// - `MorePrecision`: the result from the property that results in more precision is used.
587    /// - `LessPrecision`: the result from the property that results in less precision is used.
588    ///
589    /// Note that for values other than `Auto` the result with more precision is calculated from the [`UseIntlNumberFormatOptions::maximum_significant_digits`] and [`UseIntlNumberFormatOptions::maximum_fraction_digits`] (minimum fractional and significant digit settings are ignored).
590    rounding_priority: RoundingPriority,
591
592    /// Experimental.
593    /// Specifies the rounding-increment precision. Must be one of the following integers:
594    /// `1` (default), `2`, `5`, `10`, `20`, `25`, `50`, `100`, `200`, `250`, `500`, `1000`, `2000`, `2500`, `5000`.
595    ///
596    /// This option controls the rounding increment to be used when formatting numbers:
597    ///
598    /// - It indicates the increment at which rounding should take place relative to the calculated rounding magnitude.
599    /// - It cannot be mixed with significant-digits rounding or any setting of `rounding_priority` other than `Auto`.
600    ///
601    /// For example, if `maximum_fraction_digits` is 2 and `rounding_increment` is 5, then the number is rounded to the nearest 0.05 ("nickel rounding").
602    ///
603    /// ```
604    /// # use leptos::prelude::*;
605    /// # use leptos_use::{use_intl_number_format, UseIntlNumberFormatOptions, NumberStyle};
606    /// #
607    /// # #[component]
608    /// # fn Demo() -> impl IntoView {
609    /// let nf = use_intl_number_format(
610    ///     UseIntlNumberFormatOptions::default()
611    ///         .style(NumberStyle::Currency)
612    ///         .currency("USD")
613    ///         .maximum_fraction_digits(2)
614    ///         .rounding_increment(5),
615    /// );
616    ///
617    /// let formatted = nf.format::<f64>(11.29); // "$11.30"
618    /// let formatted = nf.format::<f64>(11.25); // "$11.25"
619    /// let formatted = nf.format::<f64>(11.22); // "$11.20"
620    /// #
621    /// # view! { }
622    /// # }
623    /// ```
624    ///
625    /// If you set `minimum_fraction_digits` and `maximum_fraction_digits`, they must set them to the same value; otherwise a `RangeError` is thrown.
626    rounding_increment: u16,
627
628    /// Experimental.
629    /// A string expressing the strategy for displaying trailing zeros on whole numbers. The default is `"auto"`.
630    ///
631    /// - `Auto`: keep trailing zeros according to `minimum_fraction_digits` and `minimum_significant_digits`.
632    /// - `StripIfInteger`: remove the fraction digits _if_ they are all zero. This is the same as `Auto` if any of the fraction digits is non-zero.
633    trailing_zero_display: TrailingZeroDisplay,
634
635    /// These properties fall into two groups: `minimum_integer_digits`, `minimum_fraction_digits`,
636    /// and `maximum_fraction_digits` in one group, `minimum_significant_digits` and `maximum_significant_digits`
637    /// in the other. If properties from both groups are specified, conflicts in the resulting
638    /// display format are resolved based on the value of the [`UseIntlNumberFormatOptions::rounding_priority`] property.
639    ///
640    /// The minimum number of integer digits to use. A value with a smaller number of integer digits
641    /// than this number will be left-padded with zeros (to the specified length) when formatted.
642    /// Possible values are from 1 to 21; the default is 1.
643    minimum_integer_digits: u8,
644
645    /// The minimum number of fraction digits to use. Possible values are from 0 to 20;
646    /// the default for plain number and percent formatting is 0;
647    /// the default for currency formatting is the number of minor unit digits provided by the
648    /// [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml)
649    /// (2 if the list doesn't provide that information).
650    #[builder(into)]
651    minimum_fraction_digits: Option<u8>,
652
653    /// The maximum number of fraction digits to use. Possible values are from 0 to 20;
654    /// the default for plain number formatting is the larger of `minimum_fraction_digits` and 3;
655    /// the default for currency formatting is the larger of `minimum_fraction_digits` and
656    /// the number of minor unit digits provided by the
657    /// [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml)
658    /// (2 if the list doesn't provide that information); the default for percent formatting is
659    /// `minimum_fraction_digits`.
660    #[builder(into)]
661    maximum_fraction_digits: Option<u8>,
662
663    /// The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.
664    #[builder(into)]
665    minimum_significant_digits: Option<u8>,
666
667    /// The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.
668    #[builder(into)]
669    maximum_significant_digits: Option<u8>,
670}
671
672impl UseIntlNumberFormatOptions {
673    /// A string with a BCP 47 language tag. Please refer to the
674    /// [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters)
675    /// for more info.
676    pub fn locale(self, locale: &str) -> Self {
677        Self {
678            locales: vec![locale.to_string()],
679            ..self
680        }
681    }
682}
683
684impl Default for UseIntlNumberFormatOptions {
685    fn default() -> Self {
686        Self {
687            locales: Default::default(),
688            compact_display: Default::default(),
689            currency: None,
690            currency_display: Default::default(),
691            currency_sign: Default::default(),
692            locale_matcher: Default::default(),
693            notation: Default::default(),
694            numbering_system: None,
695            sign_display: Default::default(),
696            style: Default::default(),
697            unit: None,
698            unit_display: Default::default(),
699            use_grouping: Default::default(),
700            rounding_mode: Default::default(),
701            rounding_priority: Default::default(),
702            rounding_increment: 1,
703            trailing_zero_display: Default::default(),
704            minimum_integer_digits: 1,
705            minimum_fraction_digits: None,
706            maximum_fraction_digits: None,
707            minimum_significant_digits: None,
708            maximum_significant_digits: None,
709        }
710    }
711}
712
713impl From<UseIntlNumberFormatOptions> for js_sys::Object {
714    fn from(options: UseIntlNumberFormatOptions) -> Self {
715        let obj = Self::new();
716
717        js!(obj["compactDisplay"] = options.compact_display);
718
719        if let Some(currency) = options.currency {
720            js!(obj["currency"] = currency);
721        }
722
723        js!(obj["currencyDisplay"] = options.currency_display);
724        js!(obj["currencySign"] = options.currency_sign);
725        js!(obj["localeMatcher"] = options.locale_matcher);
726        js!(obj["notation"] = options.notation);
727
728        if let Some(numbering_system) = options.numbering_system {
729            js!(obj["numberingSystem"] = numbering_system);
730        }
731
732        js!(obj["signDisplay"] = options.sign_display);
733        js!(obj["style"] = options.style);
734
735        if let Some(unit) = options.unit {
736            js!(obj["unit"] = unit);
737        }
738
739        js!(obj["unitDisplay"] = options.unit_display);
740        js!(obj["useGrouping"] = options.use_grouping);
741        js!(obj["roundingMode"] = options.rounding_mode);
742        js!(obj["roundingPriority"] = options.rounding_priority);
743        js!(obj["roundingIncrement"] = options.rounding_increment);
744        js!(obj["trailingZeroDisplay"] = options.trailing_zero_display);
745        js!(obj["minimumIntegerDigits"] = options.minimum_integer_digits);
746
747        if let Some(minimum_fraction_digits) = options.minimum_fraction_digits {
748            js!(obj["minimumFractionDigits"] = minimum_fraction_digits);
749        }
750        if let Some(maximum_fraction_digits) = options.maximum_fraction_digits {
751            js!(obj["maximumFractionDigits"] = maximum_fraction_digits);
752        }
753
754        if let Some(minimum_significant_digits) = options.minimum_significant_digits {
755            js!(obj["minimumSignificantDigits"] = minimum_significant_digits);
756        }
757        if let Some(maximum_significant_digits) = options.maximum_significant_digits {
758            js!(obj["maximumSignificantDigits"] = maximum_significant_digits);
759        }
760
761        obj
762    }
763}
764
765cfg_if! { if #[cfg(feature = "ssr")] {
766    /// Return type of [`use_intl_number_format`].
767    pub struct UseIntlNumberFormatReturn;
768} else {
769    /// Return type of [`use_intl_number_format`].
770    pub struct UseIntlNumberFormatReturn {
771        /// The instance of [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).
772        pub js_intl_number_format: js_sys::Intl::NumberFormat,
773    }
774}}
775
776impl UseIntlNumberFormatReturn {
777    /// Formats a number according to the [locale and formatting options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters) of this `Intl.NumberFormat` object.
778    /// See [`use_intl_number_format`] for more information.
779    /// In the browser this uses `SendWrapper` internally so the returned signal can only be used on
780    /// the same thread where this method was called.
781    pub fn format<N>(&self, number: impl Into<Signal<N>>) -> Signal<String>
782    where
783        N: Clone + Display + Send + Sync + 'static,
784        js_sys::Number: From<N>,
785    {
786        let number = number.into();
787
788        cfg_if! { if #[cfg(feature = "ssr")] {
789            Signal::derive(move || {
790                format!("{}", number.get())
791            })
792        } else {
793            let number_format = self.js_intl_number_format.clone();
794
795            Signal::derive(sendwrap_fn!(move || {
796                if let Ok(result) = number_format
797                    .format()
798                    .call1(&number_format, &js_sys::Number::from(number.get()).into())
799                {
800                    result.as_string().unwrap_or_default()
801                } else {
802                    "".to_string()
803                }
804            }))
805        }}
806    }
807
808    /// Formats a range of numbers according to the locale and formatting options of this `Intl.NumberFormat` object.
809    ///
810    /// ```
811    /// # use leptos::prelude::*;
812    /// # use leptos_use::{NumberStyle, use_intl_number_format, UseIntlNumberFormatOptions};
813    /// #
814    /// # #[component]
815    /// # fn Demo() -> impl IntoView {
816    /// let nf = use_intl_number_format(
817    ///     UseIntlNumberFormatOptions::default()
818    ///         .locale("en-US")
819    ///         .style(NumberStyle::Currency)
820    ///         .currency("USD")
821    ///         .maximum_fraction_digits(0),
822    /// );
823    ///
824    /// let formatted = nf.format_range::<i32, i32>(3, 5); // "$3 – $5"
825    ///
826    /// // Note: the "approximately equals" symbol is added if
827    /// // startRange and endRange round to the same values.
828    /// let formatted = nf.format_range::<f64, f64>(2.9, 3.1); // "~$3"
829    /// #
830    /// # view! { }
831    /// # }
832    /// ```
833    ///
834    /// ```
835    /// # use leptos::prelude::*;
836    /// # use leptos_use::{NumberStyle, use_intl_number_format, UseIntlNumberFormatOptions};
837    /// #
838    /// # #[component]
839    /// # fn Demo() -> impl IntoView {
840    /// let nf = use_intl_number_format(
841    ///     UseIntlNumberFormatOptions::default()
842    ///         .locale("es-ES")
843    ///         .style(NumberStyle::Currency)
844    ///         .currency("EUR")
845    ///         .maximum_fraction_digits(0),
846    /// );
847    ///
848    /// let formatted = nf.format_range::<i32, i32>(3, 5); // "3-5 €"
849    /// let formatted = nf.format_range::<f64, f64>(2.9, 3.1); // "~3 €"
850    /// #
851    /// # view! { }
852    /// # }
853    /// ```
854    pub fn format_range<NStart, NEnd>(
855        &self,
856        start: impl Into<Signal<NStart>>,
857        end: impl Into<Signal<NEnd>>,
858    ) -> Signal<String>
859    where
860        NStart: Clone + Display + Send + Sync + 'static,
861        NEnd: Clone + Display + Send + Sync + 'static,
862        js_sys::Number: From<NStart>,
863        js_sys::Number: From<NEnd>,
864    {
865        let start = start.into();
866        let end = end.into();
867
868        cfg_if! { if #[cfg(feature = "ssr")] {
869            Signal::derive(move || {
870                format!("{} - {}", start.get(), end.get())
871            })
872        } else {
873            let number_format = self.js_intl_number_format.clone();
874
875            Signal::derive(
876                sendwrap_fn!(move || {
877                    if let Ok(function) = js!(number_format["formatRange"]) {
878                        let function = function.unchecked_into::<js_sys::Function>();
879
880                        if let Ok(result) = function.call2(
881                            &number_format,
882                            &js_sys::Number::from(start.get()).into(),
883                            &js_sys::Number::from(end.get()).into(),
884                        ) {
885                            return result.as_string().unwrap_or_default();
886                        }
887                    }
888
889                    "".to_string()
890                })
891            )
892        }}
893    }
894
895    // TODO : Allows locale-aware formatting of strings produced by this `Intl.NumberFormat` object.
896    // pub fn format_to_parts<N>(
897    //     &self,
898    //     ,
899    //     number: impl Into<Signal<N>>,
900    // ) -> Signal<Vec<String>>
901    // where
902    //     N: Clone + 'static,
903    //     f64: From<N>,
904    // {
905    //     let number = number.into();
906    //     let number_format = self.js_intl_number_format.clone();
907    //
908    //     Signal::derive(move || {
909    //         let array = number_format.format_to_parts(number.get().into());
910    //
911    //         array
912    //             .to_vec()
913    //             .iter()
914    //             .map(|p| p.as_string().unwrap_or_default())
915    //             .collect()
916    //     })
917    // }
918}