Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

JavaScript toString Method Converts a Number to a String

The JavaScript toString method is used to convert a number to a string. It accepts a single optional parameter which specifies the base in which the number is to be represented in the string. This is a very convenient method of converting a number to a different base. If called without a parameter then the digits in the number will be converted to a string directly. Shown below is code converting a number to a string without specifying a base.

var numValue = 123;
alert("The number is " + numValue.toString());           

The output from the above code is "The number is 123". Shown below is code passing the parameter 16 to convert the number from decimal to hexadecimal.

var numValue = 123;
alert("The number is " + numValue.toString(16));  

The output from the above code is "The number is 7b". Shown below is code passing the parameter 2 to convert the number from decimal to binary.

var numValue = 213;
alert("The number is " + numValue.toString(2));

The output from the above code is "The number is 11010101". If you are simply converting digits to a string without changing the base, you can use JavaScript coercion, sometimes called "type casting". using the + symbol as shown below, JavaScript will automatically convert the number's digits to a string.

var numValue = 213;
alert("The number is " + numValue);

Or even simply:

alert("The number is " + 213); 

Coercion is when JavaScript uses its own discretion to cast a variable to another type. When you are not explicitly using coercion, as above, it can cause difficult to find errors.

More Java Script Code:
• Java Script Character Encoding and Decoding
• Java Script Data Types
• A Brief History of JavaScript
• Determine Absolute Value
• Java Script alert Message Box
• JavaScript to Concatenate Strings
• Accessing Web Page Elements
• JavaScript Math Object
• Get Webpage File Date and File Size
• The Conditional Operator

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro


Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2019 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268