number与string的转换

222 阅读1分钟
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title></title>

<style type="text/css">

</style>

<script type="text/javascript">

// number -> string

// toString()

/*

var num = 10;

var res = num.toString();

alert(typeof (num));

alert(typeof (res));

*/


// 加一个空格

/*

var num = 10;

var res = num + ""

alert(num + ", " + typeof (num));

alert(res + ", " + typeof (res));

*/


// 使用String(数字)函数

/*

var num = 10;

var res = String(num);

alert(num + ", " + typeof (num));

alert(res + ", " + typeof (res));

*/


// 没有固定精度的表示

/*

var n = 1234.56789;

var s4 = n.toFixed(2);

var s5 = n.toExponential(2); // 指数表示

var s6 = n.toPrecision(2); // 有效位数


alert(s4 + ", " + typeof(s4));

alert(s5 + ", " + typeof(s5));

alert(s6 + ", " + typeof(s6));

*/



// string -> number

// 做除了加法以外的数字运算

/*

var s = "12345";

var r = s / 1; // s - 0;

alert(s + ", " + typeof s);

alert(r + ", " + typeof r);

*/


// 使用parse系方法

// parseInt() parseFloat()

/*

var s = "08";

var r = parseInt(s);

alert(s + ", " + typeof s);

alert(r + ", " + typeof r);

*/

// parse系方法,只识别一个字符串中开始的数字,如果识别不了就返回NaN

alert(parseInt("a123abc") + 1);


// 使用Number()函数

</script>

</head>

<body>

</body>

</html>