Format Unit With Plural
formatUnitWithPlural
The formatUnitWithPlural function returns a grammatically correct unit string based on the numeric value provided simply by adding s at the end of the unit name. It optionally prefixes the unit with the number.
Pro Tips
-
This function only appends an s at the end of the unit. It does not follow any grammar rules.
-
For complex and versatile pluralization with proper grammar rules, please refer to pluralizer or Pluralizer Class instead.
Function Signature
formatUnitWithPlural(count: number, unit: string, withNumber?: boolean): string;
Parameters
count: The numeric value used to determine whether the unit should be singular or plural.unit: The base unit string (e.g.,"day","hour","month").withNumber(optional): Whether to include the number before the unit. Defaults totrue.
Return Value
Returns a properly formatted unit string, such as:
"1 day"or"2 days"ifwithNumberistrue."day"or"days"ifwithNumberisfalse.
Example Usage
With Number
import { formatUnitWithPlural } from 'nhb-toolbox';
console.log(formatUnitWithPlural(1, 'hour')); // "1 hour"
console.log(formatUnitWithPlural(3, 'day')); // "3 days"
Without Number
import { formatUnitWithPlural } from 'nhb-toolbox';
console.log(formatUnitWithPlural(1, 'minute', false)); // "minute"
console.log(formatUnitWithPlural(5, 'month', false)); // "months"
Notes
- Automatically pluralizes the unit if the absolute count is not
1. - Accepts both positive and negative numbers (e.g.,
-1is treated like1for pluralization). - Does not handle irregular plurals like
child->childreninstead it does return unit withs. For complex and versatile pluralization, please refer to pluralizer or Pluralizer Class instead.
Aliases
formatNumberWithPluralUnit: Alias forformatUnitWithPlural.formatWithPlural: Alias forformatUnitWithPlural.
Conclusion
The formatUnitWithPlural function is useful for displaying human-readable units based on dynamic counts, supporting singular and plural forms with or without the numeric prefix.