Daniel
Daniel

Reputation: 47904

How can I do math with words in jQuery?

I am trying to write a program that can do math with English words.

For example, I want to be able to do something like

"four thousand and three" + "seven thousand and twenty nine" 

and get output like

"eleven thousand and thirty two"

Is it possible to do this in jQuery?

Upvotes: 7

Views: 355

Answers (3)

Peter Olson
Peter Olson

Reputation: 142921

Yes, I have written a jQuery plug-in called Word Math that was made for this exact purpose.

For the example in your question, you can just copy and paste this code

alert($.wordMath("four thousand and three").add("seven thousand and twenty nine"));
//alerts "eleven thousand thirty two"

and voila! You've performed some word math.

Word Math can also do conversion from Javascript numbers to words and vice versa:

$.wordMath.toString(65401.90332)
// sixty five thousand four hundred one and nine tenths and three thousandths and three ten thousandths and two hundred thousandths

$.wordMath("three million four hundred and sixty seven thousand five hundred and forty two").value
// 3467542

You can read more about how to use the Word Math plugin on its readme page

EDIT: There is now a version of Word Math that does not depend on jQuery. To use it, you should download the wordMath.vanilla.min.js file on the gitHub repository instead of the wordMath.jquery.js file.

The usage of the jQuery-less version is exactly the same as the jQuery version, except that you do not need the $. prefix in the calls. In other words, instead of doing

$.wordMath("fifteen").add("eighteen")

you would instead write

wordMath("fifteen").add("eighteen")

Upvotes: 14

Brian Warfield
Brian Warfield

Reputation: 377

You can use the library but if you want to write your own code you could start with something like this.

<script type="text/javascript">

var equation = "one plus two";
var arrayOfWords =  equation.split(" ");
var functionToEvaluate = "";

for(i in arrayOfWords){
    functionToEvaluate = functionToEvaluate + GetNumericOrSymbol(arrayOfWords[i]);
}

var answer = eval(functionToEvaluate);
alert(answer);
//Then your method GetNumericOrSymbol() could so something like this.

function GetNumericOrSymbol(word){
    var assocArray = new Array();
    assocArray['one'] = 1;
    assocArray['two'] = 2;

    //rest of the numbers to nine

    assocArray['plus']='+';

    //rest of your operators

    return assocArray[word];
}
</script>

Something like taking the Array out of the function call would help optimize it. Had a lot of fun writing this.

Upvotes: 3

George Cummins
George Cummins

Reputation: 28906

As you know, you cannot perform mathematical operations on the strings themselves, so you need to start by converting your text into numerical values.

After you perform the mathematical operations on the numeric values, you can convert the values back into strings and output the result.

Upvotes: 2

Related Questions