Search code examples
javascriptstring-formattingecmascript-6template-strings

Number formatting in template strings (Javascript - ES6)


I was wondering if it is possible to format numbers in Javascript template strings, for example something like:

var n = 5.1234;
console.log(`This is a number: $.2d{n}`);
// -> 5.12

Or possibly

var n = 5.1234;
console.log(`This is a number: ${n.toString('.2d')}`);
// -> 5.12

That syntax obviously doesn't work, it is just an illustration of the type of thing I'm looking for.

I am aware of tools like sprintf from underscore.string, but this seems like something that JS should be able to do out the box, especially given the power of template strings.

EDIT

As stated above, I am already aware of 3rd party tools (e.g. sprintf) and customised functions to do this. Similar questions (e.g. JavaScript equivalent to printf/String.Format) don't mention template strings at all, probably because they were asked before the ES6 template strings were around. My question is specific to ES6, and is independent of implementation. I am quite happy to accept an answer of "No, this is not possible" if that is case, but what would be great is either info about a new ES6 feature that provides this, or some insight into whether such a feature is on its way.


Solution

  • No, ES6 does not introduce any new number formatting functions, you will have to live with the existing .toExponential(fractionDigits), .toFixed(fractionDigits), .toPrecision(precision), .toString([radix]) and toLocaleString(…) (which has been updated to optionally support the ECMA-402 Standard, though).
    Template strings have nothing to do with number formatting, they just desugar to a function call (if tagged) or string concatenation (default).

    If those Number methods are not sufficient for you, you will have to roll your own. You can of course write your formatting function as a template string tag if you wish to do so.