Cast integer to string javascript

6 ways to convert int to string in JavaScript

In this post, we will learn,6 ways to convert int to string in JavaScript.The numbers in programming language sometimes are represented as “12”.Its data type is not a number but a string.

1. Tosting() to convert int to string in JavaScript

The tostring() method takes a number or float as input and converts it into a string. It returns a string representation of the number. It takes an optional base parameter.

Читайте также:  Net snmp python примеры

The tostring() throw type errors while converting undefined and null to string.

Syntax

Base: this is an optional parameter that makes converts an input number to another base. It is an int between 2 to 36.

"50" "45.5" "num to string base 2:", "1010" "NaN" "Symbol(234)" TypeError: Cannot read property 'toString' of null TypeError: Cannot read property 'toString' of undefined

2. Template Literal to to convert int to string in JavaScript

Template literal uses back-ticks(“) to define a string, which is introduced in ES6. Earlier we used to create a string by using single quotes (‘) or double quotes (“) quotes to define a string.

It throws a type error while converting a symbol type value to a string.

Let us understand with the below example how to convert the value to a string.

Example : Converting a value to string using Template String

intnum = 50; int_to_str = `$` console.log(int_to_str) ; floatnum = 45.50; console.log(`$`) ; num_nan = NaN; console.log(`$`);

3. string () to convert int to string in JavaScript

The string() method allows us to create a primitive string type for the number passed to it as an argument. The string() method handles the NULL and undefined. It does not throw errors when NULL and undefined is passed.

JS Program to convert int to string

intnum = 50; floatnum = 45.50; num_nan = NaN; let b = null; var c ; console.log(String(intnum)); console.log(String(floatnum)); console.log(String(num_nan)); console.log(String(b)); console.log(String(c));
"50" "45.5" "NaN" "null" "undefined"

4. concatinating empty string

This is the naive way to convert a value to a string, number is concatenated with an empty string to convert. It is the fastest way to accomplish as compared to another way.

it throws a typeerror while converting a symbol type value to a string same as template literal.

Example : Converting a value to string using string() method

float = 45.50; floatnum_to_str = ''+float; num_nan = NaN; nan_tostr = ''+num_nan; console.log(num_to_str); console.log(String(floatnum_to_str)); console.log(String(nan_tostr));

5.JSON.Stringfy() to to convert int to string

JSON.Stringfy() method converts an object or value to a string.

JS Program to convert int to string

intnum = 50; floatnum = 45.50; let b = null; var c ; console.log(JSON.stringify(intnum)); console.log(JSON.stringify(floatnum)); console.log(JSON.stringify(b)); console.log(JSON.stringify(c));

6.Using tofixed() method

The tofixed() method used to convert a number to a string. It rounds the number to specified number of the decimal digits.

Syntax

Digits: an optional parameter. It specified the number of digits after the decimal place.

Convert value to string tofixed() method

In this example, we are converting a number to a string by not passing any argument to tofixed() and passing a digit

intnum = 50; floatnum = 45.503; console.log(intnum.toFixed()); console.log(floatnum.toFixed()); console.log(floatnum.toFixed(2));

Summary

We have explored 6 ways to convert int to string in JavaScript. List of functions we have used

  • Tosting() Method :The tostring() method takes a number or float as input and converts it into a string
  • Using Template Literal :It uses back-ticks(“) to define a string is introduced in ES6.
  • String() Method :The string() method allows us to create a primitive string type for the number passed to it as an argument.
  • By concatinating empty string : number is concatenated with an empty string to convert
  • Using JSON.Stringfy() : convert number to string
  • Using tofixed() method : convert given number to string.

Источник

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.

Источник

5 ways to convert a number to string in JavaScript

In JavaScript, you can represent a number as type number (ex. 12), or as a type string (ex. ’12’).But both are not same. At times while coding we might have to convert the data from one type to other and there are many ways to do that. I would like to list few of the methods I know of data conversion from number to string.

1. Using .toString() method

There is a default string method that converts the data to string. The toString() method returns the value of a String object.

myNumber = 100 myNumber.toString() // expected result: '100' noNumber = NaN noNumber.toString() // expected result: 'NaN' decNum = 122.33 decNum.toString() // expected result: "122.33" 

2. Using String()

myNumber = 99 String(myNumber) // expected result: '99' fltNumber = 25.54 String(fltNumber) // expected result: '25.54' 

3. Concatenating the Empty String

Adding empty string to the number value will convert the data to string is one of the simplest way to do the job. It is also considered to be faster than the above two when it comes to performance.

myNumber = 22 myString = '' + myNumber // expected result: '22' fltNumber = 25.54 fltString = '' + fltNumber // expected result: '25.54' 

4. Template Strings

With the introduction of template strings in ES6, injecting a number inside a String is a valid way of parsing an Integer or Float data type. This is the fastest way to convert the number to string.

myNumber = 22 flt = 50.205; string = `$`; // expected result: '50' floatString = `$`; // expected result: '50.205' 

5. Using toFixed() method

myNumber = 22 myNumber.toFixed() // expected result: '22' a = 56.9887 a.toFixed() // expected result: '57' a.toFixed(4) // expected result: '56.9887' 

Here is the comparison of the methods when it comes to the performance. Comment below if you know more ways.
Thank you

Источник

JavaScript Number toString()

The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.

Normally, you will not use it in your own code.

Syntax

Parameters

Parameter Description
radix Optional.
The base to use.
Must be an integer between 2 and 36.
Base 2 is binary
Base 8 is octal
Base 16 is hexadecimal.

Return Value

More Examples

Convert a number to a string, using base 8 (Octal):

Convert a number to a string, using base 16 (Hexadecimal):

Browser Support

toString() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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