formatting rules for numbers in knockoutjs

http://stackoverflow.com/questions/7704268/formatting-rules-for-numbers-in-knockoutjs

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script src="https://rawgithub.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js"></script>
<div data-bind="text: myValue"></div>
<div data-bind="text: myValue2"></div>

JavaScript

function formattedNumericObservable(initialValue, precision) {
    var _raw = ko.observable(initialValue),
        precision = precision || formattedNumericObservable.defaultPrecision,        
        //the dependentObservable that we will return
        result = ko.dependentObservable({
            read: function() {
               return _raw().toFixed(precision); 
            },
            write: _raw
        });
            
        //expose raw value (if necessary) for binding
        result.raw = _raw;
            
        return result;   
}

formattedNumericObservable.defaultPrecision = 1;

var viewModel = {
    myValue: formattedNumericObservable(123.55454),
    myValue2: formattedNumericObservable(222.1234, 3),
};

ko.applyBindings(viewModel);