Skip to content

Commit

Permalink
Support control of trailing zeros #236
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisala committed Feb 22, 2024
1 parent 41a11bd commit b720bf0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
31 changes: 23 additions & 8 deletions grails-app/assets/javascripts/knockout-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,22 @@
* @param precision the number of decimal places allowed.
* @returns {Computed<any>}
*/
ko.extenders.numericString = function(target, precision) {
ko.extenders.numericString = function(target, options) {
var defaults = {
decimalPlaces: 2,
removeTrailingZeros: true // backwards compatibility
};
if (_.isNumber(options)) {
options = {decimalPlaces: options};
}
options = _.extend({}, defaults, options);

function roundAndToString(value) {
var roundingMultiplier = Math.pow(10, options.decimalPlaces);
var roundedValue = Math.round(value * roundingMultiplier) / roundingMultiplier;
return roundedValue.toString();
}

//create a writable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
Expand All @@ -173,18 +188,18 @@
if (typeof val === 'string') {
val = newValue.replace(/,|\$/g, '');
}
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(val) ? 0 : parseFloat(+val),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
var current = target();
var newValueAsNum = isNaN(val) ? 0 : parseFloat(+val);

var valueToWrite = options.removeTrailingZeros ? roundAndToString(newValueAsNum) : newValueAsNum.toFixed(options.decimalPlaces);

//only write if it changed
if (valueToWrite.toString() !== current || isNaN(val)) {
target(isNaN(val) ? newValue : valueToWrite.toString());
if (valueToWrite !== current || isNaN(val)) {
target(isNaN(val) ? newValue : valueToWrite);
}
else {
if (newValue !== current) {
target.notifySubscribers(valueToWrite.toString());
target.notifySubscribers(valueToWrite);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,11 @@ class ModelJSTagLib {

def numberViewModel(JSModelRenderContext ctx) {
int decimalPlaces = ctx.dataModel.decimalPlaces ?: 2
observable(ctx, ["{numericString:${decimalPlaces}}"])

Map options = new HashMap(ctx.viewModel()?.displayOptions ?: [:])
options.decimalPlaces = decimalPlaces
String optionString = (options as JSON).toString()
observable(ctx, ["{numericString:${optionString}}"])
}

def dateViewModel(JSModelRenderContext ctx) {
Expand Down

0 comments on commit b720bf0

Please sign in to comment.