gastonmesseri / numerable

Number formatting library for Javascript and Node.js apps
MIT License
84 stars 1 forks source link

How to create custom format? #2

Closed dpyzo0o closed 3 years ago

dpyzo0o commented 3 years ago

It's not a bug report.

Is it possible to create a custom format like Numeral.js does here?

gastonmesseri commented 3 years ago

Hi @dpyzo0o , It is still not documented (and is not fully implemented), but you technically can use custom formatters in a similar way as Numeral.js does. The formatters have to be called along with the function, as a format option, following the functional intention of this library. So I encourage you to create a wrapper function in order to avoid including your custom formatter each time you call the format function. Here is an example:

format(1000.232, '0,0.00 myformat', {
  formatters: [{
    name: 'my-format',
    regexps: {
      format: /myformat/,
    },
    format: (value, pattern, options) => {
      const patternWithoutEscapedPlaceholder = pattern.replace(/myformat/, "'TESTING MY FORMAT'");
      return format(value, patternWithoutEscapedPlaceholder, options);
    },
  }],
});
// This will return '1,000.23 TESTING MY FORMAT'