Currency symbols ($, € etc.) as a unit alias?
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?
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
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?
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?
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)
};
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.