+ 3

How do I add numbers as strings using js?

I wanna code a simple calculator using commands like ‘prompt’ so that you can enter a number. The problem is that the numbers are strings and if I’m doing a task like “6+5” the result is 65. Is there any solution?

3rd Jan 2021, 4:25 PM
Leander
Leander - avatar
4 odpowiedzi
+ 2
Yes, you can parse the strings into numbers. You can use parseInt(yourStringVariable) to parse integers or you can use parseFloat(yourStringVariable) to parse floating numbers or you can use Number(yourStringVariable) to parse it. There are many options, you can even do let number = +yourStringVariable; and it will be a number data type. I recommend using parseFloat in your case.
3rd Jan 2021, 4:39 PM
Mikuláš Dovhun
Mikuláš Dovhun - avatar
+ 2
Use eval() function if you want to let a user enter the expression him self: https://www.w3schools.com/jsref/jsref_eval.asp Else, if you want to convert strings to numbers use parseFloat() global method: https://www.w3schools.com/jsref/jsref_parsefloat.asp The parseFloat() global method is probably what you are looking for since parseInt does not convert float numbers.
3rd Jan 2021, 4:31 PM
Karak10
Karak10 - avatar
+ 2
You can easily convert a string to an integer with the parseInt() function, for example: var a = "5"; var b = "6"; document.write(parseInt(a)+parseInt(b)); outputs 11
3rd Jan 2021, 4:32 PM
Martin Ed
Martin Ed - avatar
+ 1
Generally speaking, the easy way to do this is to use the Number() constructor, which will take a value and spit out a number data type, unless that value cannot be converted to a number, in which case it'll just vomit out "NaN" (Not a Number). I'd strongly recommend staying away from eval(), as that is considered extremely bad practice. The eval() function runs any code passed into it, which is a *huge* security risk later on. It's best not to get used to using that as a solution (especially if there are others!).
3rd Jan 2021, 7:15 PM
HealyUnit
HealyUnit - avatar