Photo by Gabriel Heinzer on Unsplash
Convert a string to integer/float using JS
String conversion to integer/float using Unary operators in JavaScript.
Hey Guys
I found a neat trick to convert a string to an integer/decimal (with fixed values after decimal) using JavaScript.
Let's take a string containing a whole number.
let numberAsString = "234";
numberAsString = +numberAsString;
console.log(numberAsString, typeof(numberAsString));
Output
Let's take a string containing a number as a float.
let numberAsString = "234.2323";
numberAsString = +numberAsString;
console.log(numberAsString, typeof(numberAsString));
Output
Using + before the string returns the numeric presentation of the variable, in our case it will convert the values to int/float depending on what is passed in the string.
Using this, we can dynamically convert the string containing numeric values.