mathjs icon indicating copy to clipboard operation
mathjs copied to clipboard

Currency symbols ($, € etc.) as a unit alias?

Open xxczaki opened this issue 5 years ago • 5 comments

I have the following unit:

USD: {
	definition: '0.xxx EUR'`, // This comes from an API
	aliases: ['usd', '$']
}

Unfortunately, while 10 USD to [some other unit] works, 10$ or 10 $ does not. This also doesn't work with other currency symbols. Is there a way to fix this?

xxczaki avatar Jun 06 '20 12:06 xxczaki

The expression parser allows only a limited set of characters variable names. You can customize this to also allow characters like by overriding the math.parse.isAlpha function, see docs:

https://mathjs.org/docs/expressions/customization.html#customize-supported-characters

josdejong avatar Jun 10 '20 06:06 josdejong

I'm not sure this answers it. isAlpha supports $ as a character for variables and constants, but units are still governed by their own parseUnit function.

 Unit.isValidAlpha = function isValidAlpha (c) {
    return /^[a-zA-Z]$/.test(c)
  }

Any plans on allowing currency symbols in units?

larissa-n avatar Nov 02 '21 16:11 larissa-n

Good point. So indeed you need to override both math.parse.isAlpha and math.Unit.isValidAlpha with your own version accepting too. But that works, right?

josdejong avatar Nov 03 '21 12:11 josdejong

You don't have to override math.parse.isAlpha since it it's not used in conjunction with math.Unit as it stands currently. But you're right, you can just customize math.Unit.isValidAlpha. So something like this would do:

const isUnitAlphaOriginal = math.Unit.isValidAlpha;
math.Unit.isValidAlpha = function (c, cPrev, cNext) {
   return isUnitAlphaOriginal(c, cPrev, cNext) || ['$', '€'].includes(c)
};

larissa-n avatar Nov 04 '21 10:11 larissa-n

True, you only need to adjust math.parse.isAlpha if you're using the expression parser, and you can use units without the expression parser.

josdejong avatar Nov 04 '21 19:11 josdejong