Skip to content

Commit b720bf0

Browse files
committed
Support control of trailing zeros #236
1 parent 41a11bd commit b720bf0

File tree

2 files changed

+28
-9
lines changed

2 files changed

+28
-9
lines changed

grails-app/assets/javascripts/knockout-utils.js

+23-8
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,22 @@
164164
* @param precision the number of decimal places allowed.
165165
* @returns {Computed<any>}
166166
*/
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+
168183
//create a writable computed observable to intercept writes to our observable
169184
var result = ko.computed({
170185
read: target, //always return the original observables value
@@ -173,18 +188,18 @@
173188
if (typeof val === 'string') {
174189
val = newValue.replace(/,|\$/g, '');
175190
}
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);
180195

181196
//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);
184199
}
185200
else {
186201
if (newValue !== current) {
187-
target.notifySubscribers(valueToWrite.toString());
202+
target.notifySubscribers(valueToWrite);
188203
}
189204
}
190205
}

grails-app/taglib/au/org/ala/ecodata/forms/ModelJSTagLib.groovy

+5-1
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,11 @@ class ModelJSTagLib {
624624

625625
def numberViewModel(JSModelRenderContext ctx) {
626626
int decimalPlaces = ctx.dataModel.decimalPlaces ?: 2
627-
observable(ctx, ["{numericString:${decimalPlaces}}"])
627+
628+
Map options = new HashMap(ctx.viewModel()?.displayOptions ?: [:])
629+
options.decimalPlaces = decimalPlaces
630+
String optionString = (options as JSON).toString()
631+
observable(ctx, ["{numericString:${optionString}}"])
628632
}
629633

630634
def dateViewModel(JSModelRenderContext ctx) {

0 commit comments

Comments
 (0)