English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Is there a built-in function in javascript that will convert a number, such as 234.5678 (I know the number of decimal points) to a character string, similar to parseFloat(x)? If not, can someone explain how?

2007-10-12 06:34:34 · 2 answers · asked by cidyah 7 in Computers & Internet Programming & Design

2 answers

Javascript should convert the value automatically. but I know the following works:

var num = 1234.5678;
var numString = "";
numString += num;

alert(typeof(numString); // alerts "string";
alert(numString); // alerts "1234.5678"

The String Constructor can also do this conversion
var num = 1234.5678;
var numString = String(num);
alert(typeof(numString); // alerts "string";
alert(numString); // alerts "1234.5678"

2007-10-12 07:03:38 · answer #1 · answered by Xorph 2 · 0 0

Being loosely type, JavaScript performs these conversions "automagically" in a number of ways (even when you don't mean to, if you're not careful). The simplest way is to use the "+" operator. When "+" is used between a string and a number, it is interpreted as "concatenate" not "add."

// concatenate an empty string (two apostrophes or
// two double-quotes) to the number
var strNum = '' + num // give the string equivalent

If you're including the number in a string message, just concatenate the number inline...
var msg = 'the value of num is: ' + num

2007-10-12 07:27:06 · answer #2 · answered by richarduie 6 · 0 0

fedest.com, questions and answers