preliminary release
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
// One rounding rule for every percentage shown: one decimal, half up; between 0 and 0.1
|
||||
// the first significant digit (0.04 %, not 0.0 %). Integer counts round exactly, without
|
||||
// binary floating-point surprises (1.005 → 1.0 with toFixed).
|
||||
|
||||
/** The percentage of `k` in `n`, rounded by the rule, computed from integers. */
|
||||
export function sharePercent(k: number, n: number): number {
|
||||
if (k > 0 && 1000 * k < n) return Number((100 * k / n).toPrecision(1));
|
||||
return Math.floor((2000 * k + n) / (2 * n)) / 10;
|
||||
}
|
||||
|
||||
/** A published percentage (0 to 100), rounded by the rule. */
|
||||
export function roundPercent(value: number): number {
|
||||
if (value > 0 && value < 0.1) return Number(value.toPrecision(1));
|
||||
// Snap to 9 decimals first so 12.25 published as 12.2499999999 still rounds up.
|
||||
return Math.floor(Math.round(value * 1e9) / 1e8 + 0.5) / 10;
|
||||
}
|
||||
|
||||
/** Text of a rounded percentage: «12.3», «0.04», «100.0». */
|
||||
export function percentNumber(value: number): string {
|
||||
const rounded = roundPercent(value);
|
||||
return rounded > 0 && rounded < 0.1 ? String(rounded) : rounded.toFixed(1);
|
||||
}
|
||||
|
||||
/** «12.3 %» from a published percentage, or the fallback when there is none. */
|
||||
export function percentText(value: number | null | undefined, fallback = 'No disponible'): string {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
|
||||
}
|
||||
|
||||
/** «12.3 %» from a count over its denominator. */
|
||||
export function shareText(k: number, n: number): string {
|
||||
const value = sharePercent(k, n);
|
||||
return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`;
|
||||
}
|
||||
Reference in New Issue
Block a user