parseFloat function parses a passed string and returns a number with floating point. The given function determines whether the first character in the specified string is a number, then if it’s true, the function parses the string until it reaches the end of the number, and returns the number as a number, not as a string. In other words, parseFloat makes an explicit type conversion from a string to a proper number with floating point.
var res = 90 + someVal;
var someNumber = parseFloat(someVal); var res = 90 + someNumber;
OK, now res is expectedly 120.555.
There is an alternative – Number():
var someNumber = Number(someVal);
I use parseFloat instead Number(), because in my case the value extracted from query string may contain some additional alphabetical characters. For example, I can get from query string something like “30.555oz.”. I’m too lazy to cut out the excess symbols, I prefer using parseFloat. Repeating what I said in the beginning of this article, parseFloat successfully parses a string, which starts with a string representation of a number. All symbols after last digit symbol will be ignored. That means that the string “30.555oz.” will be transformed to the number 30.555. Another string “3YQJGP7CCACF” will be transformed to 3 and so on. In contrast, Number() accepts only a valid string number without any additional symbols.
In addition I’d like to note that some people complain about a parseFloat rounding problem (e.g. here or here): when, for example, string “3.05″ turns into number 3.04999999999…. The solution is to use the toFixed function, which formats a number to use a specified number of trailing decimals. toFixed accepts the number of digits after the decimal point.
var someNumber = parseFloat('3.05'); someNumber = someNumber.toFixed(2);
toFixed helps to overcome this rounding problem, however, for justice’ sake, I need to note that we may not always know how many digits after point our initial string number had. Therefore, the usage of toFixed function with an inappropriate number of digits may affect accuracy of calculations.