fix(input-amount): support negative numbers

This commit is contained in:
Victor Kachan 2019-06-25 10:42:05 +02:00 committed by Mikhail Bashkirov
parent 0b8785ccf6
commit 83f9baa36d
4 changed files with 36 additions and 2 deletions

View file

@ -61,7 +61,7 @@ function getParseMode(value) {
*/
function parseWithLocale(value, options) {
const separator = getDecimalSeparator(options);
const regexNumberAndLocaleSeparator = new RegExp(`[0-9${separator}]`, 'g');
const regexNumberAndLocaleSeparator = new RegExp(`[0-9${separator}-]`, 'g');
let numberAndLocaleSeparator = value.match(regexNumberAndLocaleSeparator).join('');
if (separator === ',') {
numberAndLocaleSeparator = numberAndLocaleSeparator.replace(',', '.');
@ -110,7 +110,7 @@ function parseHeuristic(value) {
* @param {object} options Locale Options
*/
export function parseAmount(value, options) {
const matchedInput = value.match(/[0-9,. ]/g);
const matchedInput = value.match(/[0-9,.\- ]/g);
if (!matchedInput) {
return undefined;
}

View file

@ -10,6 +10,17 @@ storiesOf('Forms|Input Amount', module)
</lion-input-amount>
`,
)
.add(
'Negative number',
() => html`
<lion-input-amount
.errorValidators="${['required']}"
label="Amount"
.modelValue=${-123456.78}
>
</lion-input-amount>
`,
)
.add(
'Set USD as currency',
() => html`

View file

@ -54,6 +54,13 @@ describe('formatAmount()', () => {
maximumFractionDigits: 3,
}),
).to.equal('12.346');
expect(
formatAmount(-12.345678, {
locale: 'en-GB',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}),
).to.equal('-12.35');
});
it('formats the right amount of fraction digits for a certain currency', async () => {

View file

@ -112,11 +112,27 @@ describe('parseAmount()', () => {
expect(parseAmount('1 23.4')).to.equal(123.4);
});
it('parses negative numbers', () => {
expect(parseAmount('-0')).to.equal(0);
expect(parseAmount('-1')).to.equal(-1);
expect(parseAmount('-1234')).to.equal(-1234);
expect(parseAmount('-1.234,5')).to.equal(-1234.5);
expect(parseAmount('-1,234.5')).to.equal(-1234.5);
expect(parseAmount('-1.234,5678')).to.equal(-1234.5678);
expect(parseAmount('-1,234.5678')).to.equal(-1234.5678);
});
it('ignores all non-number symbols (including currency)', () => {
expect(parseAmount('€ 1,234.56')).to.equal(1234.56);
expect(parseAmount('€ -1,234.56')).to.equal(-1234.56);
expect(parseAmount('-€ 1,234.56')).to.equal(-1234.56);
expect(parseAmount('1,234.56 €')).to.equal(1234.56);
expect(parseAmount('-1,234.56 €')).to.equal(-1234.56);
expect(parseAmount('EUR 1,234.56')).to.equal(1234.56);
expect(parseAmount('EUR -1,234.56')).to.equal(-1234.56);
expect(parseAmount('-EUR 1,234.56')).to.equal(-1234.56);
expect(parseAmount('1,234.56 EUR')).to.equal(1234.56);
expect(parseAmount('-1,234.56 EUR')).to.equal(-1234.56);
expect(parseAmount('Number is 1,234.56')).to.equal(1234.56);
});