Why parseFloat in javascript returns string type for me?

社会主义新天地 提交于 2019-11-30 22:44:42

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!