Skip to content

Instantly share code, notes, and snippets.

@ctrlShiftBryan
Created August 27, 2014 15:49
Show Gist options
  • Select an option

  • Save ctrlShiftBryan/fbb547c8120903a75dcb to your computer and use it in GitHub Desktop.

Select an option

Save ctrlShiftBryan/fbb547c8120903a75dcb to your computer and use it in GitHub Desktop.
ko.extenders.precisionScale = function (target, dynamicProperty) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function (newValue) {
var current = target();
var valueToWrite = newValue;
if (valueToWrite) {
//get precision and scale
var precision = dynamicProperty.ColumnPrecision;
var scale = dynamicProperty.ColumnScale;
//turn into string and parse
var valAsString = valueToWrite.toString();
var parts = valAsString.split('.');
var integerPartString = parts[0];
var fractionalPartString = parts[1];
//store negative info
var isNegative = integerPartString.indexOf('-') > -1;
if (isNegative)
integerPartString = integerPartString.replace('-','');
//remove non alpha numeric
integerPartString = integerPartString ? integerPartString.replace(/\D/g, '') : '';
fractionalPartString = fractionalPartString ? fractionalPartString.replace(/\D/g, '') : '';
//get maximum lengths based on precision and scale
var maxIntegerPartLength = precision - scale;
var maxFractionalPartLength = scale;
//get attempt lengths
var attempedIntegerPartLength = integerPartString ? integerPartString.length : 0;
var attempedfractionalPartLength = fractionalPartString ? fractionalPartString.length : 0;
//truncated parts if needed
if (attempedIntegerPartLength > maxIntegerPartLength) {
integerPartString = integerPartString.substr(0, maxIntegerPartLength);
}
if (attempedfractionalPartLength > maxFractionalPartLength) {
fractionalPartString = fractionalPartString.substr(0, maxFractionalPartLength);
}
//put the whole value back together
var formattedValue = integerPartString;
if (fractionalPartString)
formattedValue = integerPartString + '.' + fractionalPartString;
if (isNegative)
formattedValue = '-' + formattedValue;
valueToWrite = formattedValue;
}
//if the formatted value is the same force a refresh
if (newValue !== current) {
target('');
}
target(valueToWrite);
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment