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

Convert a Number to a String

In many instances, Java Script automatically converts numbers to strings. For example, anytime you display a number using document.write or alert, Java Script automatically converts the number to a string for display.

var n = 10 + 2;
alert(n);

var n = 10 + 2;
document.write(n);

Both of the code snippets above will cause the string "12" to display.

A quick way to convert a number to a string is to use the string concatenation operator (+) as shown below.

var t = 118;
var s = t + " degrees f";
document.write(s);

The code above will display the string "118 degrees f".

You don't actually need any characters in the concatenated string to convert a number to a string, as shown below.

var n = 3.14152;
alert(typeof n);
n = 3.14152 + "";
alert(typeof n);

The fist message box will display the type of n as "number", after concatenating an empty string to the variable n, the second message box will display the type of n as "string".

The code below casts the number 3.14152 to a string by passing it to a String object constructor.

var n = 3.14152;
var s = String(n);
alert(typeof s);

The proper way to convert a number to a string is to use the Number object's toString method, as shown below.

var n = 3.14152;
s = n.toString();
alert(typeof s);

why would you want to convert a number to a string? After performing a calculation, you may need to format the result for display. The code shown below formats the number 32.6738 to $ 32.67 for display as a currency value.

var k = 32.6738;
m = k.toString();
var n = m.substring(0,m.indexOf(".") + 3);
var amt = "$ " + n;
alert(amt);

In many instances, Java Script automatically converts numbers to strings, but you can use the String object constructor or the toString method to explicitly convert a number to a string.

More Java Script Code:
• Determine Absolute Value
• Java Script Arithmetic Operators
• Use Escape to Replace Dangerous Characters
• Java Script Include a Backslash Character in a String
• Search and Replace Strings
• Java Script prompt Message Box
• Java Script Trigonometric Methods
• Window Object Properties and Methods
• Comparison Operators
• Convert a Number to a String

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-2018 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268