Skip to content

Commit 55d87e3

Browse files
feat: add formatNumber (#39)
1 parent 6f374ae commit 55d87e3

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/js/format-number.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Format a number to a human-readable string
3+
* @param num The number to format
4+
* @param decimalPlaces The number of decimal places to include in the formatted string
5+
* @returns {string}
6+
*/
7+
function formatNumber(num, decimalPlaces = 1) {
8+
if (num >= 1000000) {
9+
return (num / 1000000).toFixed(decimalPlaces) + 'M';
10+
} else if (num >= 1000) {
11+
return (num / 1000).toFixed(decimalPlaces) + 'k';
12+
} else {
13+
return num.toFixed(decimalPlaces);
14+
}
15+
}
16+
17+
// Expose to the global scope
18+
if (typeof window !== 'undefined') {
19+
window.formatNumber = formatNumber;
20+
}
21+
22+
module.exports = formatNumber;

tests/format-number.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import {
2+
describe,
3+
expect,
4+
test,
5+
} from '@jest/globals';
6+
7+
const formatNumber = require('../src/js/format-number');
8+
9+
describe('formatNumber function', () => {
10+
test.each([
11+
[1234567, 1, '1.2M'], // 1.2 million
12+
[1234567, 2, '1.23M'], // 1.23 million
13+
[1234, 1, '1.2k'], // 1.2 thousand
14+
[1234, 2, '1.23k'], // 1.23 thousand
15+
[123, 1, '123.0'], // 123 with 1 decimal place
16+
[123, 2, '123.00'], // 123 with 2 decimal places
17+
])('formats %i with %i decimal places as %s', (num, decimalPlaces, expected) => {
18+
expect(formatNumber(num, decimalPlaces)).toBe(expected);
19+
});
20+
21+
test('defaults to 1 decimal place if not provided', () => {
22+
expect(formatNumber(1234567)).toBe('1.2M');
23+
expect(formatNumber(1234)).toBe('1.2k');
24+
expect(formatNumber(123)).toBe('123.0');
25+
});
26+
});

0 commit comments

Comments
 (0)