Repository navigation
Expand file tree
/
Copy pathformatAmount.js
More file actions
72 lines (60 loc) · 1.91 KB
/
Copy pathformatAmount.js
File metadata and controls
72 lines (60 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Normalizes Stellar amount-like values to a fixed seven-decimal string.
*
* Accepts Horizon-style decimal strings, numbers, or bigint values.
* Returns the original value unchanged when it is blank or not numeric.
*
* @param {string|number|bigint|null|undefined} value
* @returns {string|number|bigint|null|undefined}
*/
function formatAmount(value) {
if (value === null || value === undefined || value === "") {
return value;
}
if (typeof value === "number") {
return Number.isFinite(value) ? value.toFixed(7) : value;
}
if (typeof value === "bigint") {
return `${value.toString()}.0000000`;
}
if (typeof value !== "string") {
return value;
}
const trimmed = value.trim();
if (!trimmed) {
return value;
}
const match = trimmed.match(/^([+-]?)(\d+)(?:\.(\d+))?$/);
if (!match) {
const numeric = Number(trimmed);
return Number.isFinite(numeric) ? numeric.toFixed(7) : value;
}
const [, sign, rawWhole, rawFraction = ""] = match;
const rounded = roundFraction(rawWhole, rawFraction, 7);
const prefix = sign === "-" && !isZeroAmount(rounded.whole, rounded.fraction) ? "-" : "";
return `${prefix}${rounded.whole}.${rounded.fraction}`;
}
function isZeroAmount(whole, fraction) {
return /^0+$/.test(whole) && /^0+$/.test(fraction);
}
function roundFraction(whole, fraction, scale) {
if (fraction.length <= scale) {
return {
whole,
fraction: fraction.padEnd(scale, "0"),
};
}
const digits = `${whole}${fraction.slice(0, scale)}`;
let combined = BigInt(digits || "0");
if (Number(fraction.charAt(scale)) >= 5) {
combined += 1n;
}
const combinedString = combined.toString().padStart(scale + 1, "0");
const wholePart = combinedString.slice(0, -scale) || "0";
const fractionPart = combinedString.slice(-scale).padStart(scale, "0");
return {
whole: wholePart,
fraction: fractionPart,
};
}
module.exports = { formatAmount };