Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 657
Daniel Avatar asked Mar 23 '12 20:03

Daniel


People also ask

What does $() mean in JavaScript?

Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $. get() .

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.

What is and $$ in JavaScript?

$ and $$ are valid variable names in JavaScript, they have no special meaning. Usually they set their value to library instances, in your example if you check the closure call, at the end of the file you'll see that $ is jQuery in this case if it is defined and $$ is cytoscape.

How to write multiplication in JavaScript?

An asterisk ( * ) is used to represent the multiplication operator.


1 Answers

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")
like image 53
Peter Olson Avatar answered Oct 05 '22 16:10

Peter Olson