模板字符串中的数字格式(Javascript - ES6)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31746166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:18:18  来源:igfitidea点击:

Number formatting in template strings (Javascript - ES6)

javascriptstring-formattingecmascript-6template-strings

提问by aquavitae

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

我想知道是否可以在 Javascript 模板字符串中格式化数字,例如:

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 sprintffrom underscore.string, but this seems like something that JS should be able to do out the box, especially given the power of template strings.

我知道像sprintffromunderscore.string这样的工具,但这似乎是 JS 应该能够开箱即用的东西,尤其是考虑到模板字符串的强大功能。

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.

如上所述,我已经知道 3rd 方工具(例如 sprintf)和定制函数可以做到这一点。类似的问题(例如JavaScript 等价于 printf/String.Format)根本没有提到模板字符串,可能是因为在 ES6 模板字符串出现之前他们就被问到了。我的问题特定于 ES6,并且与实现无关。如果是这种情况,我很高兴接受“不,这是不可能的”的答案,但最好是有关提供此功能的新 ES6 功能的信息,或了解此类功能是否在其上大大地。

采纳答案by Bergi

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).

不,ES6 没有引入任何新的数字格式功能,您将不得不接受现有的.toExponential(fractionDigits), .toFixed(fractionDigits), .toPrecision(precision),.toString([radix])toLocaleString(…)(虽然已经更新为可选地支持ECMA-402 标准)。
模板字符串与数字格式无关,它们只是对函数调用(如果标记)或字符串连接(默认)进行脱糖。

If those Numbermethods 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.

如果这些Number方法对您来说还不够,您将不得不自己动手。如果您愿意,您当然可以将格式化函数编写为模板字符串标记。

回答by userDEV

You should be able to use the toFixed() method of a number:

您应该能够使用数字的 toFixed() 方法:

var num = 5.1234;
var n = num.toFixed(2); 

回答by Filip Allberg

If you want to use ES6 tag functions here's how such a tag function would look,

如果你想使用 ES6 标签函数,这里是这样一个标签函数的样子,

function d2(pieces) {
    var result = pieces[0];
    var substitutions = [].slice.call(arguments, 1);

    for (var i = 0; i < substitutions.length; ++i) {
        var n = substitutions[i];

        if (Number(n) == n) {
            result += Number(substitutions[i]).toFixed(2);
        } else {
            result += substitutions[i];
        }

        result += pieces[i + 1];
    }

    return result;
}

which can then be applied to a template string thusly,

然后可以将其应用于模板字符串,

d2`${some_float} (you can interpolate as many floats as you want) of ${some_string}`;

that will format the float and leave the string alone.

这将格式化浮点数并保留字符串。

回答by GaryO

Here's a fully ES6 version of Filip Allberg's solution above, using ES6 "rest" params. The only thing missing is being able to vary the precision; that could be done by making a factory function. Left as an exercise for the reader.

这是上面 Filip Allberg 解决方案的完整 ES6 版本,使用 ES6 “rest” 参数。唯一缺少的是能够改变精度;这可以通过制作工厂函数来完成。留给读者作为练习。

function d2(strs, ...args) {
    var result = strs[0];
    for (var i = 0; i < args.length; ++i) {
        var n = args[i];
        if (Number(n) == n) {
            result += Number(args[i]).toFixed(2);
        } else {
            result += args[i];
        }
        result += strs[i+1];
    }
    return result;
}

f=1.2345678;
s="a string";
console.log(d2`template: ${f} ${f*100} and ${s} (literal:${9.0001})`);

回答by Eliran Malka

While formatting using template string interpolation is not available as a built-in, you can get an equivalent behavior with Intl.NumberFormat:

虽然使用模板字符串插值进行格式化不能作为内置功能使用,但您可以通过以下方式获得等效的行为Intl.NumberFormat

const format = (num, fraction = 2) => new Intl.NumberFormat([], {
  minimumFractionDigits: fraction,
  maximumFractionDigits: fraction,
}).format(num);

format(5.1234); // -> '5.12'

Note that regardless of your implementation of choice, you might get bitten by rounding errors:

请注意,无论您选择何种实现方式,您都可能会被舍入错误所困扰:

(9.999).toFixed(2) // -> '10.00'

new Intl.NumberFormat([], {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2, // <- implicit rounding!
}).format(9.999) // -> '10.00'

回答by Atombit

You can use es6 tag functions. I don't know ready for use of that.

您可以使用 es6 标签函数。我不知道准备好使用它。

It might look like this:

它可能看起来像这样:

num`This is a number: $.2d{n}`

Learn more:

学到更多: