Format numbers

289 words, 2-minute read

Numbers, such as ${ 12345.678 }, returns a native JavaScript numeric value:

Value: 12345.678.

It’s better show the number in a friendlier format with thousands separators and allow the site to be localised for different countries and languages.

Update the formatting library #

We’re going to reuse the lib/format.js function library. If you’ve not already done so, import the tacs object at the top of the file so functions can access any global property:

lib/format.js

// formatting functions
import { tacs } from 'publican';

// ...

Add the following functions if not already defined:

lib/format.js

// default language
function lang(locale) {
  return locale || tacs?.config?.language || 'en-US';
}

// friendly number format
export function number(num, locale) {

  return new Intl.NumberFormat(lang(locale), {})
    .format( num );

}

The library has already been imported into the publican.config.js configuration file and appended to the tacs.fn.format object so no additional code is required.

Use in content and templates #

A function named tacs.fn.format.number() is now available to content and templates which can output formatted numbers in any language, e.g.

<!-- en-US default -->
<p><em>Value ${ tacs.fn.format.number( 12345.678 ) }</em></p>

<!-- Spanish alternative -->
<p><em>Valor ${ tacs.fn.format.number( 12345.678, 'es-ES' ) }</em></p>

The result:

Value 12,345.678

Valor 12.345,678