在 AngularJS 中格式化浮点数而不损失精度

Formatting floating-point numbers without loss of precision in AngularJS

在 AngularJS 中,我如何在 HTML 页面上输出浮点数而不损失精度并且不使用 0 进行不必要的填充?

我考虑过 "number" ng-filter (https://docs.angularjs.org/api/ng/filter/number),但 fractionSize 参数导致固定小数位数:

{{ number_expression | number : fractionSize}}

我正在寻找在其他各种语言中被称为 "exact reproducibility"、"canonical string representation"、repr、round-trip 等的内容,但我没能找到任何类似的内容AngularJS.

例如:

您可以捕获没有尾随零的部分并将其用于正则表达式替换。大概你想保留一个尾随零(例如“78.0”)以保持整洁而不是以小数点分隔符结尾(例如“78.”)。

var s = "12304.56780000";
// N.B. Check the decimal separator
var re = new RegExp("([0-9]+\.[0-9]+?)(0*)$");
var t = s.replace(re, '');  // t = "12304.5678"
t="12304.00".replace(re, ""); // t="12304.0"

来自regex101的解释:

/([0-9]+\.[0-9]+?)(0*)$/
    1st Capturing group ([0-9]+\.[0-9]+?)
        [0-9]+ match a single character present in the list below
            Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
            0-9 a single character in the range between 0 and 9
        \. matches the character . literally
        [0-9]+? match a single character present in the list below
            Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]
            0-9 a single character in the range between 0 and 9
    2nd Capturing group (0*)
        0* matches the character 0 literally
            Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    $ assert position at end of the string

我自己偶然发现了一个明显的解决方案!完全删除 "number" ng-filter 的使用将导致 AngularJS 根据我的要求简单地将表达式转换为字符串。

所以

{{ number_expression }}

而不是

{{ number_expression | number : fractionSize}}