0

var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];

for (var i=0; i<values.length; i++) {
  if(values[i].indexOf('+')>0 || values[i].indexOf('-')>0 || values[i].indexOf('*')>0 || values[i].indexOf('/')>0){
    try{
      var evaluated = eval(values[i]);
      if(typeof evaluated === 'number'){
        console.log(evaluated);
      }
    }catch (e){
      console.error(e)
    }
  }
}

I have some math actions, it's could be plus, minus or other actions, and I need to take result for this actions. I use eval for this. But if I have zero before number like 005,75 eval is not working. How can I calculate this?

YoroDiallo
  • 345
  • 3
  • 6
  • 26

4 Answers4

2

You can split the strings and parse the numbers, and then make them into a string again to use eval

var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];
values.forEach(function(value){
    var newValue = value.split(/([\+\-\*\/])/).map(a => parseFloat(a) || a).join('');
    var evaluated = eval(newValue);
    console.log(value,"==", evaluated);
});
George
  • 2,330
  • 3
  • 15
  • 36
shawon191
  • 1,945
  • 13
  • 28
2

There are various libraries like math.js that can be used to evaluate expressions:

console.log(math.eval("0050.00024+040.04005+0.1"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.16.5/math.min.js"></script>
Slai
  • 22,144
  • 5
  • 45
  • 53
0

you should convert it to float (ex. parseFloat("005.75") = 5.75 instead of evaluating strings

Gabri T
  • 454
  • 2
  • 13
-1

Given code at Question you can use .match() to get number values, .map() and .reduce() to add the values

var values = ["50.00024+40.04005+0.1", "0050.00024+040.04005+0.1"];

var res = values.map(function(n) {
  return n.match(/[\d.]+/g).reduce(function(a, b) {
    return a + Number(b)
  }, 0)
});

console.log(res);
guest271314
  • 1
  • 15
  • 104
  • 177
  • Looking at this line `values[i].indexOf('+')>0 || values[i].indexOf('-')>0 || values[i].indexOf('*')>0 || values[i].indexOf('/')>0` the questioner is expecting other operators too. – shawon191 Oct 27 '17 at 15:14
  • @shawon191 The same approach can be used where the operator is matched using `RegExp` `/[-+*][\d.]+/g`, see also [Chrome App: Doing maths from a string](https://stackoverflow.com/questions/32982719/chrome-app-doing-maths-from-a-string) – guest271314 Oct 27 '17 at 15:19
  • I think the linked answer won't help for `*` or `/`. – shawon191 Oct 27 '17 at 15:23
  • 1
    My answer does not omit the operators. `/([\+\-\*\/])/` notice the wrapping first brackets in the regex, which are used to prevent omitting the splitting symbol. – shawon191 Oct 27 '17 at 15:30