leptos_use/
use_intl_number_format.rs

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