簡體   English   中英

在AngularJS中格式化浮點數而不會損失精度

[英]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。

例如:

  • 1 =>“1”
  • 1.2 =>“1.2”
  • 1.23456789 =>“1.23456789”

我自己偶然發現了一個明顯的解決方案! 完全刪除“數字”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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM