33
loading...
This website collects cookies to deliver better user experience
toLocaleString()
function in JavaScript. Format numbers, currencies, and units without any 3rd party localization library.toLocaleString()
method converts a number into a string, using locale format. By default, it uses locale from web browser language but you can specify it manually. number.toLocaleString(locale, options);
locale
(optional) - if not provided, then the method will use the host environment's current locale (e.g.: default browser language)options
(optional) - object with formatting options
var exampleNumber = 123456.789;
exampleNumber.toLocaleString('pl-PL');
// output: 123.456,789
number.toLocaleString('ar-EG');
// output: ١٢٣٤٥٦٫٧٨٩
const price = 123456.789;
price.toLocaleString('en-IN', {
maximumSignificantDigits: 2
});
// output: 1,23,000
undefined
as first parameter, to use default locale set in browser.const price = 30000.65;
price.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
// English output: 30,000.65
// German output: 30.000,65
// French output: 30 000,65
decimal
(default)currency
percent
unit
style
property in options object with value currency
to format number into a string.const price = 123456.789;
price.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' });
// output: 123.456,79 €
price.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
// output: ¥123,457
currencyDisplay
property to change currency formatting. Possible values are: symbol
(default)code
name
const price = 123456.789;
price.toLocaleString('de-DE', {
style: 'currency',
currencyDisplay: 'code',
currency: 'EUR'
});
// output: 123.456,79 EUR
price.toLocaleString('ja-JP', {
style: 'currency',
currencyDisplay: 'name',
currency: 'JPY'
});
// output: 123,457円
const value = 0.767;
value.toLocaleString('pl-PL', { style: 'percent' });
// output: 77%
value.toLocaleString('ar-SA', { style: 'percent' });
// output: ٧٣٪
unit
property in options object to set a desired unit.const value = 3;
value.toLocaleString('pl-PL', {
style: 'unit',
unit: 'liter'
});
// output: 3 l
unitDisplay
property to show full word instead just one letter.const value = 3;
value.toLocaleString('pl-PL', {
style: 'unit',
unit: 'liter',
unitDisplay: 'long'
});
// output: 3 litry
narrow
value in unitDisplay
.const value = 3;
value.toLocaleString('pl-PL', {
style: 'unit',
unit: 'liter',
unitDisplay: 'narrow'
});
// output: 3l
unit
property.per
keyword, like X-per-Y
. For example kilometer-per-hour
.const speed = 50.2137;
speed.toLocaleString('pt-PT', {
style: 'unit',
unit: 'kilometer-per-hour'
});
// output: 50,214 km/h
unit
property doesn't have to make sense, it accepts any combination. 😊const value = 50.2137;
value.toLocaleString('pl-PL', {
style: 'unit',
unit: 'terabyte-per-gram',
unitDisplay: "long"
});
// output: 50,214 terabajta na gram