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.
Welcome to Bucaro TecHelp!

Bucaro TecHelp
Maintain Your Computer and Use it More Effectively
to Design a Web Site and Make Money on the Web

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

Victims of Sandy Hook

Stop the Slaughter of Innocents. Congress is bought and paid for by gun lunatics and gun promotion groups. If you want to live in a safe America, help buy Congress back for America. Send a donation to Mayors Against Illegal Guns, 909 Third Avenue, 15th Floor New York, NY 10022

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.

RSS Feed RSS Feed



Follow Stephen Bucaro Follow @Stephen Bucaro


Web Design Sections

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