Formatting floating-point numbers without loss of precision in AngularJS

大城市里の小女人 提交于 2019-12-05 22:05:57

I stumbled upon an obvious solution myself! Completely removing the use of the "number" ng-filter will cause AngularJS to simply convert the expression to a string according to my requirements.

So

{{ number_expression }}

instead of

{{ number_expression | number : fractionSize}}

You can capture the part without trailing zeros and use that in a regex replace. Presumably you want to keep one trailing zero (e.g. "78.0") to keep it tidy rather than ending with a decimal separator (e.g. "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"

Explanation from 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!