|
164 | 164 | * @param precision the number of decimal places allowed.
|
165 | 165 | * @returns {Computed<any>}
|
166 | 166 | */
|
167 |
| - ko.extenders.numericString = function(target, precision) { |
| 167 | + ko.extenders.numericString = function(target, options) { |
| 168 | + var defaults = { |
| 169 | + decimalPlaces: 2, |
| 170 | + removeTrailingZeros: true // backwards compatibility |
| 171 | + }; |
| 172 | + if (_.isNumber(options)) { |
| 173 | + options = {decimalPlaces: options}; |
| 174 | + } |
| 175 | + options = _.extend({}, defaults, options); |
| 176 | + |
| 177 | + function roundAndToString(value) { |
| 178 | + var roundingMultiplier = Math.pow(10, options.decimalPlaces); |
| 179 | + var roundedValue = Math.round(value * roundingMultiplier) / roundingMultiplier; |
| 180 | + return roundedValue.toString(); |
| 181 | + } |
| 182 | + |
168 | 183 | //create a writable computed observable to intercept writes to our observable
|
169 | 184 | var result = ko.computed({
|
170 | 185 | read: target, //always return the original observables value
|
|
173 | 188 | if (typeof val === 'string') {
|
174 | 189 | val = newValue.replace(/,|\$/g, '');
|
175 | 190 | }
|
176 |
| - var current = target(), |
177 |
| - roundingMultiplier = Math.pow(10, precision), |
178 |
| - newValueAsNum = isNaN(val) ? 0 : parseFloat(+val), |
179 |
| - valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier; |
| 191 | + var current = target(); |
| 192 | + var newValueAsNum = isNaN(val) ? 0 : parseFloat(+val); |
| 193 | + |
| 194 | + var valueToWrite = options.removeTrailingZeros ? roundAndToString(newValueAsNum) : newValueAsNum.toFixed(options.decimalPlaces); |
180 | 195 |
|
181 | 196 | //only write if it changed
|
182 |
| - if (valueToWrite.toString() !== current || isNaN(val)) { |
183 |
| - target(isNaN(val) ? newValue : valueToWrite.toString()); |
| 197 | + if (valueToWrite !== current || isNaN(val)) { |
| 198 | + target(isNaN(val) ? newValue : valueToWrite); |
184 | 199 | }
|
185 | 200 | else {
|
186 | 201 | if (newValue !== current) {
|
187 |
| - target.notifySubscribers(valueToWrite.toString()); |
| 202 | + target.notifySubscribers(valueToWrite); |
188 | 203 | }
|
189 | 204 | }
|
190 | 205 | }
|
|
0 commit comments