Home  >  Article  >  Web Front-end  >  How to convert numbers to strings in JS

How to convert numbers to strings in JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-18 17:11:543809browse

This time I will show you how to convert numbers and strings in JS, and how to convert numbers and strings in JSNotesare Which ones, the following are practical cases, let’s take a look.

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <script type="text/javascript">
    var print = new Function("x", "document.write(x)");
    var println = new Function("x", "document.write(x + '<br>')");
    var n = 1.23456;
    var str = "123.456";
    println("number to String...");
    /* 加上一个空字符串 */
    println(typeof(n + ""));
    /* 使用 String 函数 */
    println(typeof(String(n)));
    /* 使用 toString() 方法 ,可以提供一个可选的参数,指定转换的基数(2 - 36),默认基数是10 */
    println(typeof n.toString(16));
    println("0x" + n.toString(16)); // 0x1.3c0c1fc8f3238
    /* 把一个数字转换为字符串,并指定小数位数 */
    println(n.toFixed(2));     // 1.23
    /* 指数表示,参数指定小数位数 */
    println(n.toExponential(1));  // 1.2e+0
    /* 参数指定有效数字的个数 */
    println(n.toPrecision(7));   // 1.234560
    println("");
    println("string to number...");
    /* 减去一个数字 0 */
    println(typeof (str - 0));
    /* 使用 Number 函数 */
    println(typeof(Number(str)));
    /* 只转换整数, 忽略舍去非数字部分,可以提供一个参数指定转换的基数(2 ~ 36)*/
    println(parseInt(" 4 line 5 row"));  // 4
    println(parseInt("row 4"));       // NaN
    println(parseInt("1111", 2));      // 15
    println(parseInt("ff", 16));      // 255
    println(parseInt("zz", 36));      // 1295
    /* 转换为浮点数 */
    println(parseFloat("1.23e-2 like"));  // 0.0123
    println(parseFloat("125"));       // 125
  </script>
</body>
</html>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

JS easily implements carousel images

How to add Vue0.1 code to Vue2.0 for use

The above is the detailed content of How to convert numbers to strings in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn