最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Why parseFloat in javascript returns string type for me? - Stack Overflow

programmeradmin2浏览0评论

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?

Here is my code

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

I need further math steps, so string type messed up... Why? How to solve? TIA

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?

Here is my code

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

I need further math steps, so string type messed up... Why? How to solve? TIA

Share Improve this question edited Oct 15, 2017 at 16:32 palaѕн 73.9k17 gold badges122 silver badges139 bronze badges asked Oct 15, 2017 at 16:29 Tony XuTony Xu 3,0914 gold badges33 silver badges46 bronze badges 1
  • 5 toFixed and toPrecision both return strings. Please read the documentation. “How to solve?” — depends on what your goal is. – Sebastian Simon Commented Oct 15, 2017 at 16:31
Add a comment  | 

2 Answers 2

Reset to default 12

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
发布评论

评论列表(0)

  1. 暂无评论