Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why parseFloat in javascript returns string type for me?

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

like image 998
Tony Xu Avatar asked Oct 15 '17 16:10

Tony Xu


People also ask

Does parseFloat return a string?

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.

What does parseFloat do in JavaScript?

The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.

What is parseInt and parseFloat in JavaScript?

JavaScript provides two methods for converting non-number primitives into numbers: parseInt() and parseFloat() . As you may have guessed, the former converts a value into an integer whereas the latter converts a value into a floating-point number.


2 Answers

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
like image 60
palaѕн Avatar answered Oct 19 '22 15:10

palaѕн


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
like image 5
Cahil Foley Avatar answered Oct 19 '22 15:10

Cahil Foley