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

Formatting floating-point numbers without loss of precision in AngularJS

本文关键字:精度 浮点数 AngularJS 格式化      更新时间:2024-01-20

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

我考虑过"数字"ng过滤器(https://docs.angularjs.org/api/ng/filter/number)但是fractionSize参数会导致固定数量的小数:

{{ number_expression | number : fractionSize}}

我正在寻找在各种其他语言中被称为"精确再现性"、"规范字符串表示"、repr、往返等的东西,但我还没能为AngularJS找到类似的东西。

例如:

  • 1=>"1"
  • 1.2=>"1.2"
  • 1.23456789=>"1.23456789"

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

所以

{{ number_expression }}

而不是

{{ number_expression | number : fractionSize}}

您可以捕获不带尾随零的部分,并在正则表达式替换中使用它。假设您希望保留一个尾随零(例如"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, '$1');  // t = "12304.5678"
t="12304.00".replace(re, "$1"); // 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