scurker/currency.js

Lib should error instead of stripping invalid characters

Opened this issue · 6 comments

I found an issue where '123.sd' is turned into '123.00'. I was expecting this to error out as it is not a valid currency value. Looking at the code I found the following test. Any insights of what is the logic of such functionality?

If the functionality has come valid case, would it be possible to have a flag that will make this case error out?

test('should strip invalid characters', t => {
  var str = currency('a1b2c3');
  t.is(parseFloat(str), 123, 'currency("a1b2c3") is 123');
});

One of the key features of currency.js is in how it accepts various inputs. a1b2c3 is probably not the best example of a test, but it's more so that the library can accept a wide range of currency formats. Internally, it's pretty agnostic on how input is parsed so if your currency string is € 1 234 567,89 or $ 1,234,567.89 it can just take the number respective of the decimal format and output something currency like regardless of what your delimiters or symbols are. Changing it to output an error would be significant breaking change at this stage.

There is a an existing errorOnInvalid flag that exists but it currently only errors on null or undefined values. It's possible we could co-opt that, but it would be difficult to determine what's a valid string without adding a lot of additional weight to the library.

I really appreciate the flexible nature of the input string and how the lib is able to deal with it, so I wouldn't want to lose that.

Perhaps one step toward this would be to error on letters? Stripping out spaces, commas, periods and currency symbols seems normal, but having the letter d in there seems weird. Perhaps though, it's to allow a currency code in the input string? I didn't see a reference to doing this anywhere in the docs, so perhaps it'd be possible to add this small check without adding the additional weight.

Unfortunately, it's not universal that a symbol is used for currency symbols. Several countries use kr as their symbol for krona or krone, while you might see USD $1 or CAN $1 to distinguish between multiple countries that use the same symbol. It's also not uncommon to drop the symbol all together in place of a country code.

However, I'd love to better understand the use cases where this would be valuable.

@ericvera I think a having strictInput or strict mode actually sounds reasonable. I need to think about what that means in relation to errorOnInvalid but that's something that could potentially be released with a 2.0 version of the library.

it's v2.0.4 as of now, shouldn't this be implemented?