taler-util: amount currency normalization

This commit is contained in:
Florian Dold 2021-12-01 18:07:27 +01:00
parent dbbe1b0a61
commit 2dc876d6d6
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B

View File

@ -151,7 +151,7 @@ export class Amounts {
} }
let fraction = first.fraction % amountFractionalBase; let fraction = first.fraction % amountFractionalBase;
for (const x of rest) { for (const x of rest) {
if (x.currency !== currency) { if (x.currency.toUpperCase() !== currency.toUpperCase()) {
throw Error(`Mismatched currency: ${x.currency} and ${currency}`); throw Error(`Mismatched currency: ${x.currency} and ${currency}`);
} }
@ -187,7 +187,7 @@ export class Amounts {
let fraction = a.fraction; let fraction = a.fraction;
for (const b of rest) { for (const b of rest) {
if (b.currency !== currency) { if (b.currency.toUpperCase() !== a.currency.toUpperCase()) {
throw Error(`Mismatched currency: ${b.currency} and ${currency}`); throw Error(`Mismatched currency: ${b.currency} and ${currency}`);
} }
if (fraction < b.fraction) { if (fraction < b.fraction) {
@ -299,7 +299,7 @@ export class Amounts {
return undefined; return undefined;
} }
return { return {
currency: res[1], currency: res[1].toUpperCase(),
fraction: Math.round(amountFractionalBase * Number.parseFloat(tail)), fraction: Math.round(amountFractionalBase * Number.parseFloat(tail)),
value, value,
}; };
@ -403,11 +403,17 @@ export class Amounts {
*/ */
static stringify(a: AmountLike): string { static stringify(a: AmountLike): string {
a = Amounts.jsonifyAmount(a); a = Amounts.jsonifyAmount(a);
const s = this.stringifyValue(a) const s = this.stringifyValue(a);
return `${a.currency}:${s}`; return `${a.currency}:${s}`;
} }
static isSameCurrency(a1: AmountLike, a2: AmountLike): boolean {
const x1 = this.jsonifyAmount(a1);
const x2 = this.jsonifyAmount(a2);
return x1.currency.toUpperCase() === x2.currency.toUpperCase();
}
static stringifyValue(a: AmountJson, minFractional: number = 0): string { static stringifyValue(a: AmountJson, minFractional: number = 0): string {
const av = a.value + Math.floor(a.fraction / amountFractionalBase); const av = a.value + Math.floor(a.fraction / amountFractionalBase);
const af = a.fraction % amountFractionalBase; const af = a.fraction % amountFractionalBase;
@ -424,6 +430,6 @@ export class Amounts {
n = (n * 10) % amountFractionalBase; n = (n * 10) % amountFractionalBase;
} }
} }
return s return s;
} }
} }