3

AngularJS では、精度を落とさず、不要な 0 のパディングなしで HTML ページに浮動小数点数を出力するにはどうすればよいですか?

「数値」の 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"
4

2 に答える 2

2

私は自分で明白な解決策を見つけました!"number" ng-filter の使用を完全に削除すると、AngularJS は要件に従って式を単純に文字列に変換します。

そう

{{ number_expression }}

それ以外の

{{ number_expression | number : fractionSize}}
于 2015-02-18T12:58:28.663 に答える
0

末尾のゼロなしで部分をキャプチャし、それを正規表現の置換で使用できます。おそらく、小数点区切り記号 (例: "78.") で終わるのではなく、1 つの末尾のゼロ (例: "78.0") を保持して整理したいと考えています。

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
于 2015-02-18T11:02:48.113 に答える