Why parseFloat in javascript returns string type for me?

后端 未结 2 939
甜味超标
甜味超标 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 07:56

    The Number.prototype.toFixed() function is supposed to return a string type as per the documentation found here.

    If you need to perform further arithmetic with the number you can coerce it back into numeric form using the Unary plus operator before the variable name (+) documented here like so:

    var oldv = parseFloat(document.getElementById('total').textContent).toFixed(2);
    
    alert(typeof oldv); // Returns string
    
    alert(typeof +oldv); // Returns number
    

提交回复
热议问题