generated from LizardByte/template-base
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6f374ae
commit 55d87e3
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/** | ||
* Format a number to a human-readable string | ||
* @param num The number to format | ||
* @param decimalPlaces The number of decimal places to include in the formatted string | ||
* @returns {string} | ||
*/ | ||
function formatNumber(num, decimalPlaces = 1) { | ||
if (num >= 1000000) { | ||
return (num / 1000000).toFixed(decimalPlaces) + 'M'; | ||
} else if (num >= 1000) { | ||
return (num / 1000).toFixed(decimalPlaces) + 'k'; | ||
} else { | ||
return num.toFixed(decimalPlaces); | ||
} | ||
} | ||
|
||
// Expose to the global scope | ||
if (typeof window !== 'undefined') { | ||
window.formatNumber = formatNumber; | ||
} | ||
|
||
module.exports = formatNumber; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { | ||
describe, | ||
expect, | ||
test, | ||
} from '@jest/globals'; | ||
|
||
const formatNumber = require('../src/js/format-number'); | ||
|
||
describe('formatNumber function', () => { | ||
test.each([ | ||
[1234567, 1, '1.2M'], // 1.2 million | ||
[1234567, 2, '1.23M'], // 1.23 million | ||
[1234, 1, '1.2k'], // 1.2 thousand | ||
[1234, 2, '1.23k'], // 1.23 thousand | ||
[123, 1, '123.0'], // 123 with 1 decimal place | ||
[123, 2, '123.00'], // 123 with 2 decimal places | ||
])('formats %i with %i decimal places as %s', (num, decimalPlaces, expected) => { | ||
expect(formatNumber(num, decimalPlaces)).toBe(expected); | ||
}); | ||
|
||
test('defaults to 1 decimal place if not provided', () => { | ||
expect(formatNumber(1234567)).toBe('1.2M'); | ||
expect(formatNumber(1234)).toBe('1.2k'); | ||
expect(formatNumber(123)).toBe('123.0'); | ||
}); | ||
}); |