use_intl_number_format
Reactive Intl.NumberFormat.
Demo
Usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
use leptos::prelude::*;
use leptos_use_intl_number_format::{use_intl_number_format, UseIntlNumberFormatOptions};
#[component]
fn Demo() -> impl IntoView {
let (number, set_number) = signal(3500);
let number_format = use_intl_number_format(UseIntlNumberFormatOptions::default());
let formatted = number_format.format::<u16>(number); // "3,500" if in US English locale
view! { }
}
Using locales
This example shows some of the variations in localized number formats. In order to get the format
of the language used in the user interface of your application, make sure to specify that language
(and possibly some fallback languages) using the locales argument:
use leptos::prelude::*;
use leptos_use_intl_number_format::{use_intl_number_format, UseIntlNumberFormatOptions};
#[component]
fn Demo() -> impl IntoView {
let number = 123456.789_f32;
// German uses comma as decimal separator and period for thousands
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default().locale("de-DE"),
);
let formatted = number_format.format::<f32>(number); // 123.456,789
// Arabic in most Arabic speaking countries uses real Arabic digits
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default().locale("ar-EG"),
);
let formatted = number_format.format::<f32>(number); // ١٢٣٤٥٦٫٧٨٩
// India uses thousands/lakh/crore separators
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default().locale("en-IN"),
);
let formatted = number_format.format::<f32>(number); // 1,23,456.789
// the nu extension key requests a numbering system, e.g. Chinese decimal
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default().locale("zh-Hans-CN-u-nu-hanidec"),
);
let formatted = number_format.format::<f32>(number); // 一二三,四五六.七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default().locales(vec!["ban".to_string(), "id".to_string()]),
);
let formatted = number_format.format::<f32>(number); // 123.456,789
view! { }
}
Using options
The results can be customized in multiple ways.
use leptos::prelude::*;
use leptos_use_intl_number_format::{NumberStyle, UnitDisplay, use_intl_number_format, UseIntlNumberFormatOptions};
#[component]
fn Demo() -> impl IntoView {
let number = 123456.789_f64;
// request a currency format
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default()
.locale("de-DE")
.style(NumberStyle::Currency)
.currency("EUR"),
);
let formatted = number_format.format::<f64>(number); // 123.456,79 €
// the Japanese yen doesn't use a minor unit
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default()
.locale("ja-JP")
.style(NumberStyle::Currency)
.currency("JPY"),
);
let formatted = number_format.format::<f64>(number); // ¥123,457
// limit to three significant digits
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default()
.locale("en-IN")
.maximum_significant_digits(3),
);
let formatted = number_format.format::<f64>(number); // 1,23,000
// Formatting with units
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default()
.locale("pt-PT")
.style(NumberStyle::Unit)
.unit("kilometer-per-hour"),
);
let formatted = number_format.format::<i32>(50); // 50 km/h
let number_format = use_intl_number_format(
UseIntlNumberFormatOptions::default()
.locale("en-GB")
.style(NumberStyle::Unit)
.unit("liter")
.unit_display(UnitDisplay::Long),
);
let formatted = number_format.format::<i32>(16); // 16 litres
view! { }
}
For an exhaustive list of options see UseIntlNumberFormatOptions.
Formatting ranges
Apart from the format method, the format_range method can be used to format a range of numbers.
Please see UseIntlNumberFormatReturn::format_range
for details.
Server-Side Rendering
Make sure you follow the instructions in Server-Side Rendering.
Since Intl.NumberFormat is a JavaScript API it is not available on the server. That’s why
it falls back to a simple call to format!() on the server.
Installation
cargo add leptos-use-intl-number-format
Options
UseIntlNumberFormatOptions
Options for use_intl_number_format.
Every option is set with a builder method of the same name, e.g. UseIntlNumberFormatOptions::default().locales(...). See also the API docs.
locales
Type: Vec<String>
A vec of strings, each with a BCP 47 language tag. Please refer to the MDN Docs for more info.
compact_display
Type: CompactDisplay
Only used when UseIntlNumberFormatOptions::notation is Compact. Takes either Short (default) or Long.
currency
Type: Option<String>
The currency to use in currency formatting.
Possible values are the ISO 4217 currency codes, such as “USD” for the US dollar, “EUR” for the euro,
or “CNY” for the Chinese RMB — see the Current currency & funds code list.
There is no default value; if the style is Currency, the currency property must be provided.
currency_display
Type: CurrencyDisplay
How to display the currency in currency formatting. The default is Symbol.
Symbol: use a localized currency symbol such as €.NarrowSymbol: use a narrow format symbol (“$100” rather than “US$100”).Code: use the ISO currency code.Name: use a localized currency name such as"dollar".
currency_sign
Type: CurrencySign
In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign.
You can enable this formatting by setting this option to Accounting. The default value is Standard.
locale_matcher
Type: LocaleMatcher
The locale matching algorithm to use. Possible values are Lookup and BestFit; the default is "BestFit".
For information about this option, see the Intl page.
notation
Type: Notation
The formatting that should be displayed for the number. The default is "standard".
Standard: plain number formatting.Scientific: order-of-magnitude for formatted number.Engineering: exponent of ten when divisible by three.Compact: string representing exponent; SeeUseIntlNumberFormatOptions::compact_display.
numbering_system
Type: Option<String>
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".
sign_display
Type: SignDisplay
When to display the sign for the number. The default is Auto.
Auto: sign display for negative numbers only, including negative zero.Always: always display sign.ExceptZero: sign display for positive and negative numbers, but not zero.Negative: sign display for negative numbers only, excluding negative zero. ExperimentalNever: never display sign.
style
Type: NumberStyle
The formatting style to use. The default is Decimal.
Decimalfor plain number formatting.Currencyfor currency formatting.Percentfor percent formatting.Unitfor unit formatting.
unit
Type: Option<String>
The unit to use in unit formatting, Possible values are core unit identifiers,
defined in UTS #35, Part 2, Section 6.
A subset of units
from the full list
was selected for use in ECMAScript.
Pairs of simple units can be concatenated with “-per-” to make a compound unit.
There is no default value; if the style is Unit, the unit property must be provided.
unit_display
Type: UnitDisplay
The unit formatting style to use in unit formatting. The default is Short.
Long(e.g.,16 litres).Short(e.g.,16 l).Narrow(e.g.,16l).
use_grouping
Type: NumberGrouping
Experimental.
Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.
The default is Auto.
Always: display grouping separators even if the locale prefers otherwise.Auto: display grouping separators based on the locale preference, which may also be dependent on the currency.None: do not display grouping separators.Min2: display grouping separators when there are at least 2 digits in a group.
rounding_mode
Type: RoundingMode
Experimental.
Options for rounding modes. The default is HalfExpand.
Ceil: round toward +∞. Positive values round up. Negative values round “more positive”.Floorround toward -∞. Positive values round down. Negative values round “more negative”.Expand: round away from 0. The magnitude of the value is always increased by rounding. Positive values round up. Negative values round “more negative”.Trunc: round toward 0. This magnitude of the value is always reduced by rounding. Positive values round down. Negative values round “less negative”.HalfCeil: ties toward +∞. Values above the half-increment round likeCeil(towards +∞), and below likeFloor(towards -∞). On the half-increment, values round likeCeil.HalfFloor: ties toward -∞. Values above the half-increment round likeCeil(towards +∞), and below likeFloor(towards -∞). On the half-increment, values round likeFloor.HalfExpand: ties away from 0. Values above the half-increment round likeExpand(away from zero), and below likeTrunc(towards 0). On the half-increment, values round likeExpand.HalfTrunc: ties toward 0. Values above the half-increment round likeExpand(away from zero), and below likeTrunc(towards 0). On the half-increment, values round likeTrunc.HalfEven: ties towards the nearest even integer. Values above the half-increment round likeExpand(away from zero), and below likeTrunc(towards 0). On the half-increment values round towards the nearest even digit.
These options reflect the ICU user guide, where Expand and Trunc map to ICU “UP” and “DOWN”, respectively. The rounding modes example demonstrates how each mode works.
rounding_priority
Type: RoundingPriority
Experimental.
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:
Auto: the result from the significant digits property is used (default).MorePrecision: the result from the property that results in more precision is used.LessPrecision: the result from the property that results in less precision is used.
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).
rounding_increment
Type: u16
Experimental.
Specifies the rounding-increment precision. Must be one of the following integers:
1 (default), 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000.
This option controls the rounding increment to be used when formatting numbers:
- It indicates the increment at which rounding should take place relative to the calculated rounding magnitude.
- It cannot be mixed with significant-digits rounding or any setting of
rounding_priorityother thanAuto.
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”).
use leptos::prelude::*;
use leptos_use_intl_number_format::{use_intl_number_format, UseIntlNumberFormatOptions, NumberStyle};
#[component]
fn Demo() -> impl IntoView {
let nf = use_intl_number_format(
UseIntlNumberFormatOptions::default()
.style(NumberStyle::Currency)
.currency("USD")
.maximum_fraction_digits(2)
.rounding_increment(5),
);
let formatted = nf.format::<f64>(11.29); // "$11.30"
let formatted = nf.format::<f64>(11.25); // "$11.25"
let formatted = nf.format::<f64>(11.22); // "$11.20"
view! { }
}
If you set minimum_fraction_digits and maximum_fraction_digits, they must set them to the same value; otherwise a RangeError is thrown.
trailing_zero_display
Type: TrailingZeroDisplay
Experimental.
A string expressing the strategy for displaying trailing zeros on whole numbers. The default is "auto".
Auto: keep trailing zeros according tominimum_fraction_digitsandminimum_significant_digits.StripIfInteger: remove the fraction digits if they are all zero. This is the same asAutoif any of the fraction digits is non-zero.
minimum_integer_digits
Type: u8
These properties fall into two groups: minimum_integer_digits, minimum_fraction_digits,
and maximum_fraction_digits in one group, minimum_significant_digits and maximum_significant_digits
in the other. If properties from both groups are specified, conflicts in the resulting
display format are resolved based on the value of the UseIntlNumberFormatOptions::rounding_priority property.
The minimum number of integer digits to use. A value with a smaller number of integer digits than this number will be left-padded with zeros (to the specified length) when formatted. Possible values are from 1 to 21; the default is 1.
minimum_fraction_digits
Type: Option<u8>
The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn’t provide that information).
maximum_fraction_digits
Type: Option<u8>
The maximum number of fraction digits to use. Possible values are from 0 to 20;
the default for plain number formatting is the larger of minimum_fraction_digits and 3;
the default for currency formatting is the larger of minimum_fraction_digits and
the number of minor unit digits provided by the
ISO 4217 currency code list
(2 if the list doesn’t provide that information); the default for percent formatting is
minimum_fraction_digits.
minimum_significant_digits
Type: Option<u8>
The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.
maximum_significant_digits
Type: Option<u8>
The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.