Number filter would return incorrect value when fractional part had leading zeros.

This commit is contained in:
Misko Hevery
2011-03-19 09:48:52 +05:30
parent 4295b3dded
commit d6eba8f39f
3 changed files with 45 additions and 18 deletions

View File

@@ -1,6 +1,8 @@
<a name="0.9.17"><a/>
# <angular/> 0.9.17 vegetable-reanimation (in progress) #
### Bug Fixes
- Number filter would return incorrect value when fractional part had leading zeros.
<a name="0.9.16"><a/>

View File

@@ -62,7 +62,7 @@
*/
angularFilter.currency = function(amount){
this.$element.toggleClass('ng-format-negative', amount < 0);
return '$' + angularFilter['number'].apply(this, [amount, 2]);
return '$' + angularFilter.number.apply(this, [amount, 2]);
};
/**
@@ -108,28 +108,39 @@ angularFilter.number = function(number, fractionSize){
if (isNaN(number) || !isFinite(number)) {
return '';
}
fractionSize = typeof fractionSize == $undefined ? 2 : fractionSize;
var isNegative = number < 0;
number = Math.abs(number);
var pow = Math.pow(10, fractionSize);
var text = "" + Math.round(number * pow);
var whole = text.substring(0, text.length - fractionSize);
whole = whole || '0';
var frc = text.substring(text.length - fractionSize);
text = isNegative ? '-' : '';
for (var i = 0; i < whole.length; i++) {
fractionSize = isUndefined(fractionSize)? 2 : fractionSize;
var isNegative = number < 0,
pow = Math.pow(10, fractionSize),
whole = '' + number,
formatedText = '',
i;
if (whole.indexOf('e') > -1) return whole;
number = Math.round(number * pow) / pow;
fraction = ('' + number).split('.');
whole = fraction[0];
fraction = fraction[1] || '';
if (isNegative) {
formatedText = '-';
whole = whole.substring(1);
}
for (i = 0; i < whole.length; i++) {
if ((whole.length - i)%3 === 0 && i !== 0) {
text += ',';
formatedText += ',';
}
text += whole.charAt(i);
formatedText += whole.charAt(i);
}
if (fractionSize > 0) {
for (var j = frc.length; j < fractionSize; j++) {
frc += '0';
if (fractionSize) {
while(fraction.length < fractionSize) {
fraction += '0';
}
text += '.' + frc.substring(0, fractionSize);
formatedText += '.' + fraction.substring(0, fractionSize);
}
return text;
return formatedText;
};

View File

@@ -52,6 +52,20 @@ describe('filter', function() {
expect(number(Number.NaN)).toEqual('');
expect(number("1234.5678")).toEqual('1,234.57');
expect(number(1/0)).toEqual("");
expect(number(1, 2)).toEqual("1.00");
expect(number(.1, 2)).toEqual("0.10");
expect(number(.01, 2)).toEqual("0.01");
expect(number(.001, 3)).toEqual("0.001");
expect(number(.0001, 3)).toEqual("0.000");
expect(number(9, 2)).toEqual("9.00");
expect(number(.9, 2)).toEqual("0.90");
expect(number(.99, 2)).toEqual("0.99");
expect(number(.999, 3)).toEqual("0.999");
expect(number(.9999, 3)).toEqual("1.000");
expect(number(1e50, 0)).toEqual("1e+50");
expect(number(1234.567, 0)).toEqual("1,235");
expect(number(1234.567, 1)).toEqual("1,234.6");
expect(number(1234.567, 2)).toEqual("1,234.57");
});
});