In AngularJS how do I output a floating point number on an HTML page without loss of precision and without unnecessary padding with 0's?
I've considered the "number" ng-filter (https://docs.angularjs.org/api/ng/filter/number) but the fractionSize parameter causes a fixed number of decimals:
{{ number_expression | number : fractionSize}}
I'm looking for what in various other languages is referred to as "exact reproducibility", "canonical string representation", repr, round-trip, etc. but I haven't been able to find anything similar for AngularJS.
For example:
- 1 => "1"
- 1.2 => "1.2"
- 1.23456789 => "1.23456789"
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
来源:https://stackoverflow.com/questions/28580343/formatting-floating-point-numbers-without-loss-of-precision-in-angularjs