forked from HospitalRun/hospitalrun-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-format.js
71 lines (66 loc) · 2.14 KB
/
number-format.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import Ember from 'ember';
export default Ember.Mixin.create({
/**
* Given an array and property, total all of the property values in the array and return the value.
* @param array Array|String either the actual array or the property name of the array on this object.
* @param propertyName String the property name in the array values to total.
* @param number that contains at most two decimal places.
*/
_calculateTotal(array, propertyName) {
let arrayItems;
let total = 0;
if (Ember.isArray(array)) {
arrayItems = array;
} else {
arrayItems = this.get(array);
}
total = arrayItems.reduce(function(previousValue, lineItem) {
return previousValue += this._getValidNumber(Ember.get(lineItem, propertyName));
}.bind(this), 0);
return this._numberFormat(total, true);
},
/**
* Determine if number passed in is actually a number. If it is, return the number; otherwise return 0.
* @param number the number to valdiate.
* @returns number a valid number.
*/
_getValidNumber(number) {
if (Ember.isEmpty(number) || isNaN(number)) {
return 0;
} else {
return Number(number);
}
},
/**
* Return a formatted number with a maximum of two digits
* @param value number to format
* @param returnAsNumber boolean to denote if formatted number should be returned
* as a number instead of a string
* @returns String|Number a formatted String or number containing the formatted number.
*/
_numberFormat(value, returnAsNumber) {
let returnValue;
if (!Ember.isEmpty(value)) {
if (isNaN(value)) {
return;
}
if (Math.round(value) === value) {
returnValue = Number(value).toString();
} else {
returnValue = this._round100(value).toFixed(2);
}
if (returnAsNumber) {
return Number(returnValue);
} else {
return returnValue.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');
}
}
},
_validNumber(number) {
return (!Ember.isEmpty(number) && !isNaN(number) && number > 0);
},
_round100(number) {
let tempNumber = 100 * number;
return Math.round(tempNumber) / 100;
}
});