Skip to content

Instantly share code, notes, and snippets.

@chilversc
Last active December 15, 2015 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilversc/5255213 to your computer and use it in GitHub Desktop.
Save chilversc/5255213 to your computer and use it in GitHub Desktop.
Format observable as a number with a specific precision
<p>value: <strong data-bind="text: value"></strong></p>
<p>type: <strong data-bind="text: type"></strong></p>
<p>value: <input data-bind="value: value" /></p>
<p>formatted value: <strong data-bind="text: value.formatted"></strong></p>
<p>formatted type: <strong data-bind="text: formattedType"></strong></p>
<p>formatted value: <input data-bind="value: value.formatted" /></p>
ko.subscribable.fn.numeric = function(precision) {
var multiplier = Math.pow(10, precision);
var base = this;
var result = ko.computed({
read: base,
write: function(newValue) {
var parsed = parseFloat(newValue);
if (isNaN(parsed)) parsed = 0;
var rounded = Math.round(parsed * multiplier) / multiplier;
var current = base();
if (rounded !== current) {
base(rounded);
} else {
base.notifySubscribers(rounded);
}
}
});
result(this());
result.formatted = ko.computed({
write: result,
read: function() {
return base().toFixed(rounded);
}
});
return result;
};
function AppViewModel() {
this.value = ko.observable(15.2472).numeric(2);
this.type = ko.computed(function() {
return Object.prototype.toString.call(this.value());
}, this);
this.formattedType = ko.computed(function() {
return Object.prototype.toString.call(this.value.formatted());
}, this);
}
ko.applyBindings(new AppViewModel());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment