Reputation: 1541
I've seen RP Niemeyer's answer here: Formatting rules for numbers in KnockoutJS but it doesn't seem to fit my situation.
My viewmodel is tightly bound with breeze entities for a start, so I cannot easily mess with the individual table fields. There are c. 40 fields that contain numerical impact calculation results, often to 9 or 10 decimal places. It is essential that the raw result is left untouched in the viewmodel.
RP Niemeyer's "extend" based solution seems to suit more a situation where the observable is manually created. I'd like to be able to do the formatting within the html data-bind itself as this allows me to leave things untouched in the database and just limit the display of the calculation to 3 or 4 decimal places.
I'd like to be able to do:
<div data-bind="text: myValue, precision: 1"></div>
using the extend model such as this if possible?
ko.extenders.numeric = function(target, precision) {
var result = target;
result.formatted = ko.dependentObservable({
read: function() {
return target().toFixed(precision);
},
write: target
});
return result.formatted;
};
but as it is, this currently doesn't work so I'm probably missing something really obvious.
Upvotes: 1
Views: 10962
Reputation: 114802
This answer: Formatting rules for numbers in KnockoutJS contains a numericText
binding that might work in your scenario.
Using a binding is definitely helpful in scenarios where it is not easy or convenient to hook into the creation of the observables/properties of your view model.
Upvotes: 2