Home > Blockchain >  js get result of 2 or more numbers with mathematical expressions
js get result of 2 or more numbers with mathematical expressions

Time:07-26

I have a counting-Discord bot which works perfectly fine, but i want to add some specials. Users should can use mathematical expressions like ;-;/;*, but i can't get the result of the string

example: console.log( "14 2") or console.log(Number.parseInt( "1 3*5-1")) all equals NaN or just the first number.

i just found on another stackoverflow question how i can if it's a number like true and false, but not the result.

CodePudding user response:

You could just use math.js:

console.log(math.evaluate("14 2"))
console.log(math.evaluate("1 3*5-1"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.0.1/math.js"></script>

CodePudding user response:

You're adding strings and expecting a number result. You can't convert a string like "14 2" into an expression.

The methods you've described are valid, but they can only convert a string into a number, not a complete expression.

So, you can do something like this:

const result = Number("14")   Number ("2");

Which is effectively the same as this:

const result =  "14"    "2"

Or this:

const result = Number.parseInt("14")   Number.parseInt("2")

But I think that the Number() method is a little more readable than either.

To get your input into the correct syntax, you may need to use something like string.Split()

  • Related