Almighty Dee
Almighty Dee

Reputation: 119

How to calculate all numbers with percentage in a string?

I'm working on logic for my calculator. How do I replace all numbers with % with an actual value in a string format?

For example:

const foo = "5%+5%+123+6%"

into

0.05 + 0.05 + 123 + 0.06

so if I used eval() function it would calculate and the output would be:

130.43565

Upvotes: 1

Views: 253

Answers (1)

Nitheesh
Nitheesh

Reputation: 20006

Use String.replaceAll with eval

Replace % with /100 and use eval on the replaced string

const foo = "5%+5%+123+6%";
const replacedString = foo.replaceAll('%', '/100');
console.log(eval(replacedString));

Upvotes: 2

Related Questions