xp-forge / handlebars-templates

Handlebars templates for XP web frontends
1 stars 0 forks source link

Add web.frontend.helpers.Numbers to format numbers and percentages #5

Closed thekid closed 2 years ago

thekid commented 3 years ago

See #1

Formatting numbers

// Default: Use "." as decimal separator, no thousands separator
$engine= new Handlebars($templates, new Numbers());

// German notation
$engine= new Handlebars($templates, new Numbers(decimals: ',', thousands: '.'));

Given a (float)1234.5, the results are as follows:

{{number n}}            => 1,234.5 (Uses as many decimals as present)
{{number n decimals=0}} => 1,235 (Rounds)
{{number n decimals=2}} => 1,234.50

Formatting percentages

// Default: Use "%" sign directly behind number
$engine= new Handlebars($templates, new Numbers());

// German notation, including a space between number and "%" sign
$engine= new Handlebars($templates, new Numbers(percent: '# %'));

Given a (float)0.749, the results are as follows:

{{percent n}}            => 74.9% (Uses as many decimals as present)
{{percent n decimals=0}} => 75% (Rounds)
{{percent n decimals=2}} => 74.90%

Formatting counts

{{count n "no items" "one item" "# items"}}

Handles special cases for 0 items or 1 item.