solvit.io

Add two strings in JavaScript as if they were numbers

Solution #1

Use parseInt() and parseFloat() to turn the strings into integers and floats respectively:

var a = '2';
var b = '1.14';

var result = parseInt(a) + parseFloat(b);
// result = 3.14
Solution #2

Use the unary operator to transform a string into a number:

var a = '2';
var b = '1.14';

var result = +a + +b;
// result = 3.14
Find more solutions about: