Javascript integer to string functions

JavaScript Number toString: How to Convert Number to String

JavaScript Number toString() method is “used to convert any number type value into its string type representation”.

To convert a number or integer to a string in JavaScript, you can use the “Number.toString()” method. For example, my_string = toString(my_int).

Syntax

Parameters

base : It is the base parameter that defines the base where the integer is represented in the string. Must be an integer between 2 and 36.

Return Value

The number.toString() function returns a string representing the specified Number object.

Example

The toString() is a built-in method that accepts a radix argument, an optional argument, and converts a number to a string.

let a = 11; let b = 11.00; let c = 11.21; let d = 19; let opA = a.toString(2); let opB = b.toString(2); let opC = c.toString(2); let opD = d.toString(2); console.log(opA, typeof (opA)); console.log(opB, typeof (opB)); console.log(opC, typeof (opC)); console.log(opD, typeof (opD));
1011 string 1011 string 1011.00110101110000101000111101011100001010001111011 string 10011 string

You can see that we converted int to string in the base of 2.

The num.toString() is fast and better than the + concatenation.

Converting a number to a string with base 8

To convert an integer to a string with base 8, use the toString() method by passing 8 as a parameter.

let a = 11; let b = 11.00; let c = 11.21; let d = 19; let opA = a.toString(8); let opB = b.toString(8); let opC = c.toString(8); let opD = d.toString(8); console.log(opA, typeof (opA)); console.log(opB, typeof (opB)); console.log(opC, typeof (opC)); console.log(opD, typeof (opD));
13 string 13 string 13.1534121727024366 string 23 string

After changing the base, you can see that our output is different.

Converting a number to a string with base 16

To convert an integer to a string with base 16, use the toString() method by passing 16 as a parameter.

let a = 11; let b = 11.00; let c = 11.21; let d = 19; let opA = a.toString(16); let opB = b.toString(16); let opC = c.toString(16); let opD = d.toString(16); console.log(opA, typeof (opA)); console.log(opB, typeof (opB)); console.log(opC, typeof (opC)); console.log(opD, typeof (opD));
b string b string b.35c28f5c28f6 string 13 string

Источник

JavaScript конвертируем числа в строки

Управление данными является одной из фундаментальных концепций программирования. Из-за этого JavaScript предлагает множество инструментов для анализа различных типов данных, что позволяет легко обмениваться форматами данных. В частности, в этой статье я расскажу о том, как преобразовать число в строку. В другой статье я также расскажу, как преобразовать строку в число в JavaScript.

Сравнение типов данных в JavaScript

JavaScript — это универсальный язык, который позволяет программисту контролировать, насколько строгой будет типизация данных.

Читайте также:  Python with open function

Существует два основных способа сравнения между двумя структурами / элементами данных: два знака равенства (==) или три знака равенства (===).

При использовании двух знаков равенства переменные сравниваются только по их содержанию. В этом примере будет использоваться троичный оператор, который является предпочтительным.

let a = 10; let b = '10'; a == b ? console.log('Equal!') : console.log('Different!'); // Equal!

С другой стороны, при использовании трех знаков равенства переменные сравниваются по содержанию и типу данных:

let a = 50; let b = '50'; a === b ? console.log('Equal!') : console.log('Different!'); // Different!

Преобразование числа в строку

В JavaScript есть несколько встроенных методов, которые обеспечивают преобразование числового типа данных в строку, которые отличаются только производительностью и удобочитаемостью.

.toString()

Метод .toString(), который принадлежит объекту Number.prototype, принимает целое число или число с плавающей запятой и преобразует его в тип String.

Есть несколько способов вызова этого метода. Если число (основание) передается в качестве параметра методу .toString(), число будет проанализировано и преобразовано в это базовое число:

let a = 20 a.toString(); // '20' 50 .toString(); // '50' (60).toString(); // '60' (7).toString(2); // '111' (7 в двоичном представлении)

String()

Метод String() создает примитивный тип String для переданного ему числа:

let a = 30; String(a); // '30' String(24); // '24' String(35.64); // '35.64'

Основное отличие здесь состоит в том, что объект String не выполняет никаких базовых преобразований, как Number.toString().

Шаблон строки

С введением шаблонных строк в ES6 введение числа внутри String является допустимым способом парсинга типа данных Integer или Float:

let num = 50; let flt = 50.205; let string = `$`; // '50' let floatString = `$`; // '50.205'

Конкатенация пустой строки

Наконец, что не менее важно, есть отличный способ создать строку из числа. Возможно, это один из наиболее ориентированных на производительность способов, хотя некоторая читаемость нарушена:

В зависимости от браузера, на котором работает этот код, это может быть самый быстрый способ преобразования числа в строку. Но также имейте в виду, что этот метод не всегда возвращает желаемую строку. Например:

Заключение

Есть много действительных способов манипулирования данными. Программист сам решает, какой из них выбрать, выбирая производительность, а не читабельность или баланс между ними.

Источник

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.

Читайте также:  Src bootstrap min css

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.

Источник

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.

Читайте также:  Python print with new line

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.

Источник

Оцените статью