- JavaScript Number Format
- 1. Number Formatting Introduction
- 2. Number Format Javascript — Decimal Precision
- 3. JavaScript Number Format with Commas
- 3.1. Using toLocaleString() Method
- 3.2. Custom Function For Comma Separation
- 4. JavaScript Number Format Currency
- 5. Conclusion
- Форматирование чисел на js. Как сделать пробелы в цене?
- Войдите, чтобы написать ответ
- Как из коллекции, получить Input в котором произошло изменение?
- Number.prototype.toLocaleString()
- Синтаксис
- Параметры
- Примеры
- Пример: использование toLocaleString
- Пример: проверка поддержки аргументов locales и options
- Пример: использование аргумента locales
- Пример: использование аргумента options
- Производительность
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
JavaScript Number Format
In the article javascript number format, you will learn how to format numbers in JavaScript using some built-in and custom functions. We also work on precision and rounding of numbers.
1. Number Formatting Introduction
In JavaScript, we do not have integer , float , or double data types for numbers like in Java, C, or C++.
Instead, JavaScript uses a Number data type which is always double. The number data type is used to represent numeric values which represent both integer and floating-point numbers.
While programming we generally face situations like converting a long float value to a precision of 2 or 3. Like 3.141592 => 3.14 .
And sometimes you have to convert a general big number into a comma-separated number like 1000000000 => 1,000,000,000 or convert a number to some currency system, like 100 => $100 .
These problems are shown in the image below and can be solved by formatting numbers.
2. Number Format Javascript — Decimal Precision
While doing some complex calculations the numbers that we play with are generally in a long decimal format which is not readable. So we round these decimal points to a certain precision.
JavaScript provides a built-in method Number.toFixed() to format a number to a specified number of decimal places.
The toFixed() method takes 1 argument which is the number of decimal places to be precise.
let num = 12.345678; // default toFixed() method console.log(num.toFixed()); // 12 // 2 decimal places console.log(num.toFixed(2)); // 12.35 // 3 decimal places console.log(num.toFixed(3)); // 12.346 // 6 decimal places console.log(num.toFixed(4)); // 12.3457
You can also expand the number by giving a large number fixed place value.
let num = 34.567; console.log(num.toFixed(5)); // 34.56700 console.log(num.toFixed(10)); // 34.5670000000
3. JavaScript Number Format with Commas
To format a number with a comma means to separate the digits of a number by a comma at every 3rd digit like 123456789 => 1,234,567,890 .
This way it becomes quite easy to read the number in terms of thousands, millions, billions, etc.
Another style of separating number is by placing comma at like 123456789 => 1,23,45,67,890 . First comma at 3rd digit, then all at every 2nd digit.
3.1. Using toLocaleString() Method
These formats can be achieved by using the num.toLocaleString() method.
It accepts 2 optional arguments: locale and options .
The default value of locale is en-US .
The locale can be any of the following:
let num = 7323452568.283; // US system en-US var usFormat = num.toLocaleString('en-US'); console.log(usFormat); // 7,323,452,568.283 // India system hi-IN var inFormat = num.toLocaleString('hi-IN'); console.log(inFormat); // 7,32,34,52,568.283 // Egypt system ar-EG var egFormat = num.toLocaleString('ar-EG'); console.log(egFormat); // ٧٬٣٢٣٬٤٥٢٬٥٦٨٫٢٨٣
The position of the comma can be changed by different locales like the ‘en-US’ separates numbers with a comma at every 3 digits while ‘hi-IN’ uses a comma at every 2 digits (the last 3 digits are not separated).
3.2. Custom Function For Comma Separation
You can also create your own custom function that takes a number and returns a comma-separated number.
Our Javascript function will accept a number and return a comma-separated number at every 3 digits.
The steps to create the function are as follows:
- Check if the number is decimal. If it is decimal, then take digits before the decimal point because we only need to place a comma before the decimal point.
- Check if the number is negative. If it is negative, then remove the sign for now.
- Create a loop to iterate through the number and place a comma at every 3 digits.
- Add sign back if it was negative. Also, add a decimal point and decimal digits if it was decimal.
- Finally, return the number.
// Custom function to separate comma function separateComma(val) < // remove sign if negative var sign = 1; if (val < 0) < sign = -1; val = -val; >// trim the number decimal point if it exists let num = val.toString().includes('.') ? val.toString().split('.')[0] : val.toString(); let len = num.toString().length; let result = ''; let count = 1; for (let i = len - 1; i >= 0; i--) < result = num.toString()[i] + result; if (count % 3 === 0 && count !== 0 && i !== 0) < result = ',' + result; >count++; > // add number after decimal point if (val.toString().includes('.')) < result = result + '.' + val.toString().split('.')[1]; >// return result with - sign if negative return sign < 0 ? '-' + result : result; >let num1 = 12345678; console.log(separateComma(num1)); // decimal number let num2 = -723694769.2343; console.log(separateComma(num2));
The same function can be created using the regular expression and replace method.
function commaSeparateNumber(val) < // remove sign if negative var sign = 1; if (val < 0) < sign = -1; val = -val; >// trim the number decimal point if it exists let num = val.toString().includes('.') ? val.toString().split('.')[0] : val.toString(); while (/(\d+)(\d)/.test(num.toString())) < // insert comma to 4th last position to the match number num = num.toString().replace(/(\d+)(\d)/, '$1' + ',' + '$2'); > // add number after decimal point if (val.toString().includes('.')) < num = num + '.' + val.toString().split('.')[1]; >// return result with - sign if negative return sign < 0 ? '-' + num : num; >// decimal number let num1 = 77799; console.log(commaSeparateNumber(num1)); // decimal number let num2 = -72364769.1234; console.log(commaSeparateNumber(num2));
4. JavaScript Number Format Currency
JavaScript has a built-in method that can be used to format numbers for currency, it is Intl.NumberFormat() .
It is part of the Intl (international) object. The Intl.NumberFormat() method creates an object that is language sensitive and can be used to format numbers for currency.
It accepts 2 optional arguments: locale (en-US, hi-IN, etc) and options ().
const number = 76346.45; // United state $ let num = new Intl.NumberFormat('en-US', < style: 'currency', currency: 'USD' >).format(number); console.log(num); // Indian rupee ₹ num = new Intl.NumberFormat('hi-IN', < style: 'currency', currency: 'INR' >).format(number); console.log(num);
The same is also achievable using the toLocaleString() method.
var number = 76346.45; // request a currency format var num = number.toLocaleString('hi-IN', < style: 'currency', currency: 'INR' >) console.log(num); // United state $ num = number.toLocaleString('en-US', < style: 'currency', currency: 'USD' >) console.log(num);
5. Conclusion
In this article, we learned number format javascript methods. JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl.NumberFormat() method to format the number with currency.
You can also create your own custom function to format the number. This article covers all types of number conversion.
Форматирование чисел на js. Как сделать пробелы в цене?
Подскажите, как можно с помощью js сделать пробел в числах?
У меня такая ситуация:
Нужно чтобы при вводе 10200 выводилось число 10 200 руб.
Спасибо!
Вероятно это то что искал!
Но есть вопрос, в документации ничего не нашел.
Если у меня нет старой цены — то у меня было пустое место, а теперь из-за скрипта появился везде перечеркнутый нолик.
Можно от него избавиться как-то?
Я пробую, но ничего не выходит(((
Alex_vs_Predator, самое простое и верное — не выводить div.price с пустой ценой, если старая цена не указана
const price = 10200; const formattedPrice = price.toLocaleString('ru', );
function number_format( number, decimals, dec_point, thousands_sep ) < // Format a number with grouped thousands var i, j, kw, kd, km; if( isNaN(decimals = Math.abs(decimals)) )< decimals = 2; >if( dec_point == undefined ) < dec_point = ","; >if( thousands_sep == undefined ) < thousands_sep = "."; >i = parseInt(number = (+number || 0).toFixed(decimals)) + ""; if( (j = i.length) > 3 ) < j = j % 3; >else < j = 0; >km = (j ? i.substr(0, j) + thousands_sep : ""); kw = i.substr(j).replace(/(\d)(?=\d)/g, "$1" + thousands_sep); kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : ""); return km + kw + kd; >
Войдите, чтобы написать ответ
Как из коллекции, получить Input в котором произошло изменение?
Number.prototype.toLocaleString()
Метод toLocaleString() возвращает строку с языкозависимым представлением числа.
Новые аргументы locales и options позволяют приложениям определять язык, чьё поведение и соглашения по форматированию которого оно хочет использовать. В старых реализациях, игнорирующих аргументы locales и options , используемая локаль и форма возвращённой строки целиком зависит от реализации.
Синтаксис
numObj.toLocaleString([locales[, options]])
Параметры
Проверьте раздел Совместимость с браузерами, чтобы увидеть, какие браузеры поддерживают аргументы locales и options , и Пример: проверка поддержки аргументов locales и options для определения этой возможности.
Примечание: API интернационализации ECMAScript, реализованное в Firefox 29, добавляет аргумент locales к методу Number.toLocaleString() . Если этот аргумент равен undefined , этот метод возвращает локализованные цифры на языке, определяемом ОС, в то время, как предыдущие версии Firefox возвращали цифры на английском языке. Это изменение было помечено, как регрессия, затрагивающая обратную совместимость, которая скоро может быть исправлена. (баг 999003)
Примеры
Пример: использование toLocaleString
При базовом использовании без указания локали возвращается строка, отформатированная в соответствии с локалью и опциями по умолчанию.
var number = 3500; console.log(number.toLocaleString()); // Отобразит '3,500' в локали U.S. English
Пример: проверка поддержки аргументов locales и options
Аргументы locales и options поддерживаются ещё не всеми браузерами. Для проверки того, поддерживает ли их уже реализация, можно затребовать несуществующую метку языка и проверить, будет ли выброшено исключение RangeError :
function toLocaleStringSupportsLocales() var number = 0; try number.toLocaleString('i'); > catch (e) return e.name === 'RangeError'; > return false; >
Пример: использование аргумента locales
Этот пример показывает некоторые локализованные числовые форматы. Для получения формата языка, используемого в пользовательском интерфейсе вашего приложения, убедитесь, что вы указали этот язык (и, возможно, несколько запасных языков) через аргумент locales :
var number = 123456.789; // В Германии в качестве разделителя целой и дробной части используется запятая, а в качестве разделителя разрядов - точка console.log(number.toLocaleString('de-DE')); // → 123.456,789 // В России в качестве разделителя целой и дробной части используется запятая, а в качестве разделителя разрядов - пробел console.log(number.toLocaleString('ru-RU')); // → 123 456,789 // В большинстве арабоговорящих стран используют настоящие арабские цифры console.log(number.toLocaleString('ar-EG')); // → ١٢٣٤٥٦٫٧٨٩ // В Индии используют разделители для тысяч/лакх/крор console.log(number.toLocaleString('en-IN')); // → 1,23,456.789 // Ключ расширения nu запрашивает систему нумерации, например, китайскую десятичную console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec')); // → 一二三,四五六.七八九 // Если запрашиваемый язык может не поддерживаться, например // балийский, откатываемся на запасной язык, в данном случае индонезийский console.log(number.toLocaleString(['ban', 'id'])); // → 123.456,789
Пример: использование аргумента options
Результат, предоставляемый методом toLocaleString() , может быть настроен с помощью аргумента options :
var number = 123456.789; // Запрашиваем формат валюты console.log(number.toLocaleString('de-DE', style: 'currency', currency: 'EUR' >)); // → 123.456,79 € console.log(number.toLocaleString('ru-RU', style: 'currency', currency: 'RUB' >)); // → 123 456,79 ₽ // Японская йена не использует младшие единицы console.log(number.toLocaleString('ja-JP', style: 'currency', currency: 'JPY' >)) // → ¥123,457 // Ограничиваем до трёх значащих цифр console.log(number.toLocaleString('en-IN', maximumSignificantDigits: 3 >)); // → 1,23,000
Производительность
При форматировании большого количества чисел лучшим вариантом будет создание объекта NumberFormat и использование функции, предоставляемой его свойством NumberFormat.format .
Спецификации
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 22 февр. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.