![](/img/trans.png)
[英]Loss of floating-point precision in JavaScript arrays as they get really large?
[英]Formatting floating-point numbers without loss of precision in AngularJS
在AngularJS中,如何在不丟失精度的情況下在HTML頁面上輸出浮點數,並且沒有不必要的填充0?
我已經考慮了“數字”ng-filter( https://docs.angularjs.org/api/ng/filter/number ),但是fractionSize參數會產生固定的小數:
{{ number_expression | number : fractionSize}}
我正在尋找各種其他語言被稱為“精確再現性”,“規范字符串表示”,repr,往返等等,但我還沒有找到任何類似的AngularJS。
例如:
我自己偶然發現了一個明顯的解決方案! 完全刪除“數字”ng-filter的使用將導致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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.