josdejong / mathjs

An extensive math library for JavaScript and Node.js
https://mathjs.org
Apache License 2.0
14.38k stars 1.24k forks source link

A way to handle currency units and number #1295

Closed stoplion closed 5 years ago

stoplion commented 6 years ago

Is there a way to handle something like 5 EUR + 2 and return 7 EUR? I'm following the currency example and currency [+-/*] currency works great. I'm trying to handle this sort of like soulver does and infers the answer is a currency too. But currently this (5 EUR + 2) causes an error.

josdejong commented 6 years ago

Yes, you have to specify what currency the 2 has, like 5 EUR + 2 EUR.

stoplion commented 6 years ago

Gotcha. Sounds like this is a situation where I'd need to preprocess the line and add the currency unit to the missing term.

josdejong commented 5 years ago

Yes you could do preprocessing if you want to change this behavior. Function parse and method .transform(...) could be of help there, see docs: http://mathjs.org/docs/expressions/expression_trees.html

It may be tricky though, you have a lot of possible cases which you have to handle to make things consistent, like 5 EUR + 2 + 4, 5 EUR + (2), 5 EUR - 2, 5 EUR + 2 USD + 4, etc.