JSFiddle - React, Tailwind, and code Playground
HTML
<div>
Foo: <input data-bind="value: foo" />
</div>
<div>
Bar: <input data-bind="value: bar" />
</div>
JavaScript
var viewModel = function(){
var self = this;
self.foo = ko.observable(1).extend({ numeric: 1 });
self.bar = ko.observable(1);
self.bar.extend({ numeric: 1 });
};
ko.extenders.numeric = function (target, precision) {
//create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
write: function (newValue) {
var current = target(),
valueToWrite = null;
if (!isNaN(newValue) && newValue) {
valueToWrite = parseFloat(newValue).toFixed(precision);
}
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
});
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
ko.applyBindings(new viewModel());