Difference parseInt() and parseFloat()
Converting a string to a float in Javascript?
javascript - What is the difference between Number(...) and parseFloat(...) - Stack Overflow
When does parseFloat decide to round?
Videos
I can't use parseFloat(). I am so far doing the obvious by checking each character, but I feel there has to be a more elegant way! My function needs to act exactly the same as parseFloat() does. Can anyone help?
The internal workings are not that different, as @James Allardic already answered. There is a difference though. Using parseFloat, a (trimmed) string starting with one or more numeric characters followed by alphanumeric characters can convert to a Number, with Number that will not succeed. As in:
parseFloat('3.23abc'); //=> 3.23
Number('3.23abc'); //=> NaN
In both conversions, the input string is trimmed, by the way:
parseFloat(' 3.23abc '); //=> 3.23
Number(' 3.23 '); //=> 3.23
No. Both will result in the internal ToNumber(string) function being called.
From ES5 section 15.7.1 (The Number Constructor Called as a Function):
When
Numberis called as a function rather than as a constructor, it performs a type conversion...Returns a Number value (not a Number object) computed by
ToNumber(value)if value was supplied, else returns+0.
From ES5 section 15.1.2.3 (parseFloat (string)):
... If neither
trimmedStringnor any prefix oftrimmedStringsatisfies the syntax of aStrDecimalLiteral(see 9.3.1) ...
And 9.3.1 is the section titled "ToNumber Applied to the String Type", which is what the first quote is referring to when it says ToNumber(value).
Update (see comments)
By calling the Number constructor with the new operator, you will get an instance of the Number object, rather than a numeric literal. For example:
typeof new Number(10); //object
typeof Number(10); //number
This is defined in section 15.7.2 (The Number Constructor):
When
Numberis called as part of anewexpression it is a constructor: it initialises the newly created object.
I'm using parseFloat and am a bit confused about when it decides to round.
parseFloat("34.799999999999997") returns 34.8 parseFloat("34.79") returns 34.79
Why is the first rounded to one decimal place and the second is left alone?