Skip to content

Commit 8abec48

Browse files
committed
feat: format the output using statistics
1 parent eafc4e7 commit 8abec48

3 files changed

Lines changed: 43 additions & 3 deletions

File tree

src/commands/convert.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
to,
1212
toDate,
1313
useDuration,
14+
useStatistic,
1415
} from '../helper';
1516
import formatDate from '../helper/_internal/format-date';
1617
import createPalette from '../helper/craete-palette';
@@ -96,7 +97,7 @@ async function convert(
9697
ensure(!err, 'TIMEOUT_RATE');
9798
ensure(rate.data, 'INVALID_RATE');
9899
spinner.succeed(i18n('CMD_MSG_FETCH_RATE', convertOptions));
99-
return print(yellow(rate.data.toFixed(2)));
100+
return print(yellow(useStatistic(rate.data)));
100101
}
101102

102103
const numericAmount = Number(amount);
@@ -115,8 +116,8 @@ async function convert(
115116
ensure(result.data, 'INVALID_CONVERT');
116117
spinner.succeed(i18n('CMD_MSG_FETCH_RATE', convertOptions));
117118
return print(
118-
yellow(numericAmount.toFixed(2)),
119-
yellow(result.data.toFixed(2)),
119+
yellow(useStatistic(numericAmount, { precision: 2 })),
120+
yellow(useStatistic(result.data, { precision: 2 })),
120121
);
121122
}
122123

src/helper/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ export { default as isValidCode } from './is-valid-code';
88
export { default as to } from './to';
99
export { default as toDate } from './to-date';
1010
export { default as useDuration } from './use-duration';
11+
export { default as useStatistic } from './use-statistic';

src/helper/use-statistic.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
export interface StatisticOptions {
2+
groupSeparator?: string;
3+
decimalSeparator?: string;
4+
precision?: number;
5+
}
6+
7+
function useStatistic(
8+
value: string | number,
9+
{
10+
groupSeparator = ',',
11+
decimalSeparator = '.',
12+
precision,
13+
}: StatisticOptions = {},
14+
) {
15+
const val = String(value);
16+
const cells = val.match(/^(-?)(\d*)(\.(\d+))?$/);
17+
if (!cells) return 'Invalid Number';
18+
19+
const negative = cells[1];
20+
let int = cells[2] || '0';
21+
let decimal = cells[4] || '';
22+
23+
int = int.replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator);
24+
25+
if (typeof precision === 'number') {
26+
decimal = decimal
27+
.padEnd(precision, '0')
28+
.slice(0, precision > 0 ? precision : 0);
29+
}
30+
31+
if (decimal) {
32+
decimal = `${decimalSeparator}${decimal}`;
33+
}
34+
35+
return `${negative}${int}${decimal}`;
36+
}
37+
38+
export default useStatistic;

0 commit comments

Comments
 (0)