What is the difference between Number(…) and parseFloat(…)

前端 未结 5 1432
Happy的楠姐
Happy的楠姐 2020-12-05 18:04

What is the difference between parseInt(string) and Number(string) in JavaScript has been asked previously.

But the answers basically focused on the radix

5条回答
  •  盖世英雄少女心
    2020-12-05 18:34

    Please excuse me posting yet another answer, but I just got here via a Google search and did not find all of the details that I wanted. Running the following code in Node.js:

    var vals = ["1", "1.1", "0", "1.1abc", "", " ", null];
    for(var i = 0; i < vals.length; i++){
      var ifTest = false;
      if(vals[i])
      {
        ifTest = true;
      }
      console.log("val=" + vals[i] + ", Number()=" + Number(vals[i])+ ", parseFloat()=" + parseFloat(vals[i]) + ", if()=" + ifTest);
    }
    

    gives the following output:

    val=1, Number()=1, parseFloat()=1, if()=true
    val=1.1, Number()=1.1, parseFloat()=1.1, if()=true
    val=0, Number()=0, parseFloat()=0, if()=true
    val=1.1abc, Number()=NaN, parseFloat()=1.1, if()=true
    val=, Number()=0, parseFloat()=NaN, if()=false
    val= , Number()=0, parseFloat()=NaN, if()=true
    val=null, Number()=0, parseFloat()=NaN, if()=false
    

    Some noteworthy takeaways:

    1. If protecting with an if(val) before trying to convert to number, then parseFloat() will return a number except in the whitespace case.
    2. Number returns a number in all cases except for non-numeric characters aside from white-space.

    Please feel free to add any test cases that I may be missing.

提交回复
热议问题