Why parseFloat in javascript returns string type for me?

后端 未结 2 946
甜味超标
甜味超标 2021-01-06 07:22

I searched and only found this one related to my question, but not exactly the same, as I\'m using toFixed rather than toPrecision. Why does toPrecision return a String?

2条回答
  •  难免孤独
    2021-01-06 08:07

    As mentioned in docs, toFixed returns

    A string representing the given number using fixed-point notation

    In case you need to use the returned result as a number, you can use built-in object Number:

    var oldv = parseFloat(Math.PI).toFixed(2);
    
    console.log( oldv );
    console.log( typeof oldv ); // returns string
    
    var num = Number(oldv);
    console.log( num );
    console.log( typeof num );  // returns number

提交回复
热议问题