-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
Showing
1 changed file
with
17 additions
and
3 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 |
---|---|---|
@@ -1,12 +1,26 @@ | ||
import type {I18n} from '@lingui/core' | ||
|
||
import {isWeb} from '#/platform/detection' | ||
|
||
// `@formatjs/intl-numberformat/polyfill` doesn't support `roundingMode`, and | ||
// we'd ideally want `roundingMode: trunc` to properly display shortened counts | ||
// without it being rounded up, which can be misleading for follower count. | ||
const truncateRounding = (num: number): number => { | ||
if (num < 1_000) { | ||
return num | ||
} | ||
|
||
const factor = Math.floor((Math.log10(num) - 3) / 3) * 3 + 2 | ||
const pow = 10 ** factor | ||
|
||
return Math.trunc(num / pow) * pow | ||
} | ||
|
||
export const formatCount = (i18n: I18n, num: number) => { | ||
return i18n.number(num, { | ||
return i18n.number(isWeb ? num : truncateRounding(num), { | ||
notation: 'compact', | ||
maximumFractionDigits: 1, | ||
// `1,953` shouldn't be rounded up to 2k, it should be truncated. | ||
// @ts-expect-error: `roundingMode` doesn't seem to be in the typings yet | ||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingmode | ||
roundingMode: 'trunc', | ||
}) | ||
} |