Javascript number value to string

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.

Источник

Number.prototype.toString()

The toString() method returns a string representing the specified number value.

Try it

Syntax

Parameters

An integer in the range 2 through 36 specifying the base to use for representing the number value. Defaults to 10.

Return value

A string representing the specified number value.

Exceptions

Thrown if radix is less than 2 or greater than 36.

Description

The Number object overrides the toString method of Object ; it does not inherit Object.prototype.toString() . For Number values, the toString method returns a string representation of the value in the specified radix.

For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a through f are used.

If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a — sign, not the two’s complement of the number value.

Both 0 and -0 have «0» as their string representation. Infinity returns «Infinity» and NaN returns «NaN» .

If the number is not a whole number, the decimal point . is used to separate the decimal places. Scientific notation is used if the radix is 10 and the number’s magnitude (ignoring sign) is greater than or equal to 10 21 or less than 10 -6 . In this case, the returned string always explicitly specifies the sign of the exponent.

.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" 

The toString() method requires its this value to be a Number primitive or wrapper object. It throws a TypeError for other this values without attempting to coerce them to number values.

Because Number doesn’t have a [@@toPrimitive]() method, JavaScript calls the toString() method automatically when a Number object is used in a context expecting a string, such as in a template literal. However, Number primitive values do not consult the toString() method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial toString() implementation.

Number.prototype.toString = () => "Overridden"; console.log(`$1>`); // "1" console.log(`$new Number(1)>`); // "Overridden" 

Examples

Using toString()

const count = 10; console.log(count.toString()); // "10" console.log((17).toString()); // "17" console.log((17.2).toString()); // "17.2" const x = 6; console.log(x.toString(2)); // "110" console.log((254).toString(16)); // "fe" console.log((-10).toString(2)); // "-1010" console.log((-0xff).toString(2)); // "-11111111" 

Converting radix of number strings

If you have a string representing a number in a non-decimal radix, you can use parseInt() and toString() to convert it to a different radix.

const hex = "CAFEBABE"; const bin = parseInt(hex, 16).toString(2); // "11001010111111101011101010111110" 

Beware of loss of precision: if the original number string is too large (larger than Number.MAX_SAFE_INTEGER , for example), you should use a BigInt instead. However, the BigInt constructor only has support for strings representing number literals (i.e. strings starting with 0b , 0o , 0x ). In case your original radix is not one of binary, octal, decimal, or hexadecimal, you may need to hand-write your radix converter, or use a library.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript Number to String – How to Use toString to Convert an Int into a String

Nathan Sebhastian

Nathan Sebhastian

JavaScript Number to String – How to Use toString to Convert an Int into a String

The toString() method is a built-in method of the JavaScript Number object that allows you to convert any number type value into its string type representation.

How to Use the toString Method in JavaScript

To use the toString() method, you simply need to call the method on a number value. The following example shows how to convert the number value 24 into its string representation. Notice how the value of the str variable is enclosed in double quotation marks:

var num = 24; var str = num.toString(); console.log(num); // 24 console.log(str); // "24"

You can also call the toString() method immediately on a number value, but you need to add parentheses () to wrap the value or JavaScript will respond with an Invalid or unexpected token error.

The toString() method can also convert floating and negative numbers as shown below:

24.toString(); // Error: Invalid or unexpected token (24).toString(); // "24" (9.7).toString(); // "9.7" (-20).toString(); // "-20"

Finally, the toString() method also accepts the radix or base parameter. The radix allows you to convert a number from the decimal number system (base 10) to a string representing the number in other number systems.

Valid number systems for conversion include:

  • Binary system (base 2) that has 2 digits, 0 and 1
  • Ternary system (base 3) that has 3 digits 0, 1, and 2
  • Quaternary system (base 4) that has 4 digits, 0, 1, 2 and 3
  • And so on up to the Hexatridecimal system (base 36) that has the combination of Arabic numerals 0 to 9 and Latin letters A to Z

The radix parameters accept a number type data with values ranging from 2 to 36 . Here’s an example of converting the decimal number 5 to its binary number (base 2) representation:

var str = (5).toString(2); console.log(str); // "101"

The decimal number 5 from the code above is converted to its binary number equivalent of 101 and then converted to a string.

How to Use Other Data Types with the toString() Method

Aside from converting the number type, the toString() method is also available for converting other data types into their string representations.

For example, you can convert an array type into its string representation as follows:

var arr = [ "Nathan", "Jack" ]; var str = arr.toString(); console.log(str); // "Nathan,Jack"

Or a boolean type to string as shown below:

var bool = true; var str = bool.toString(); console.log(str); // "true"

But I think you will most often use the toString() method to convert a number to a string instead of the others. That’s what I usually do, too 🙂

Thanks for reading this tutorial

You may also be interested in other JavaScript tutorials that I’ve written, including Rounding Numbers with toFixed() Method and Calculating Absolute Value with Math.abs() . They are two of the most commonly asked JavaScript problems.

I also have a free newsletter about web development tutorials (mostly JavaScript-related).

Nathan Sebhastian

Nathan Sebhastian

JavaScript Full Stack Developer currently working with fullstack JS using React and Express. Nathan loves to write about his experience in programming to help other people.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Читайте также:  Python games for kids
Оцените статью