Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

How do I evaluate the mathematical expression within a string and assign it to a numerical value in angularJS?

Eg: var value = 10;

var someValue = "Math.min(value * 0.22, 106800)". I need someValue to be a valid integer of 2.2.

Is this something which can be done by angularJS?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Use eval.

var value = 10;
var someValue = eval("Math.min(value * 0.22, 106800)");
console.log(someValue);

And it will be printed in console 2.2

share|improve this answer
1  
I would highly suggest not doing this if it's a dynamic string from user input. You might consider using Angular's $eval method instead. – jedd.ahyoung Nov 14 '13 at 5:23

One way of doing this would be by injecting 'Math' into your scope and using it in say a controller

$scope.Math = window.Math;

Here's a fiddle: http://jsfiddle.net/bxE79/1/

share|improve this answer
    
i like your solution better. you could run Math functions from the scope as well.. like this. jsfiddle.net/ayDAn – joshkurz Nov 14 '13 at 19:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.