As mentioned in the title of this post. We will be exploring a few methods you can use to cast strings into numbers and avoid being trapped in a hell of methods.
parseInt( ) vs parseFloat( )
First of all, when talking of string casting we can't avoid mentioning these very well-known methods.
So, for the ones who are new to javascript, let me tell you, that these methods are used to convert a string into an integer number "parseInt( )" or a float number "parseFloat( )" respectively.
But, there is a tiny problem with both, you have to be aware of the type of number you want to operate with from the beginning because parsing to an incorrect number can produce a lot of mistakes, that can be super harmful to your business.
const stringNumber = "45.1"
// output -> 45 (is not a string anymore)
const int = parseInt(stringNumber)
// output -> 45.1 (is not a string anymore, and it is float)
const float = parseFloat(stringNumber)
Number( )
This is directly an instance of the javascript's Number class.
Number( ), is one of the most recommended ways to parse strings in numbers since is legible enough to be in large-scale code bases and its functionality can be clearly understood by its name also formats a string in Integer or Float automatically.
const stringIntegerNumber = "45"
const stringFloatNumber = "45.1"
// output -> 45 (is not a string anymore)
const int = Number(stringIntegerNumber)
// output -> 45.1 (is not a string anymore, and it is float)
const float = Number(stringFloatNumber)
Unary operator (+)
Maybe in this selection of methods to transform a string into a number. This is definitely the weirdest, since isn't actually a JavaScript method or class but, instead a special operator.
As Number( ), the unary operator does the same functionality, but it has better performance if the people you work with have never read JavaScript's documentation this way can be not enough legible.
const stringIntegerNumber = "45"
const stringFloatNumber = "45.1"
// output -> 45 (is not a string anymore)
const int = +stringIntegerNumber
// output -> 45.1 (is not a string anymore, and it is float)
const float = +stringFloatNumber
If you don't understand what's going on let me tell you that this method works by adding a "+" operator immediately before a string with a numeric value (if there are spaces between "+" is considered the classic sum operator)
Top comments (0)