+ 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?
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.
+ 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.
+ 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
+ 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!).