Search code examples
jqueryknockout.jsknockout-mapping-plugin

Formatting Negative Numbers in Brackets in knockout.js


How can I format a negative percentage and display in parentheses using knockout.js?

function suppressNonNumeric(val,bindingName, allBindingsAccessor) 
{
    return allBindingsAccessor.has(bindingName) && ko.utils.unwrapObservable(allBindingsAccessor.get(bindingName)) && (typeof val === 'undefined' || val === null || isNaN(val));
}

ko.bindingHandlers.percent = {
positions : ko.observable(2),
update : function(element, valueAccessor, allBindingsAccessor) {
    return ko.bindingHandlers.text.update(element, function() {
        var tempVal = ko.utils.unwrapObservable(valueAccessor());
        if(suppressNonNumeric(tempVal,'suppressNull', allBindingsAccessor) )
        {
            return '';
        }
        var value = +(tempVal || 0),
        positions = ko.utils.unwrapObservable(allBindingsAccessor.has('positions') ?    allBindingsAccessor.get('positions') : ko.bindingHandlers.percent.positions);
        return value.toFixed(positions).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") ;
    });

How do i modify this function to check if value is negative eg: -23.44 and change to(23.44)


Solution

  • If you still need it, I think the following should work:

    ...
    var value = Math.abs(tempVal), // tempVal is defined and is a number, we checked it in suppressNonNumeric
    ...
    return '(' value.toFixed(positions).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") + ')';
    ...