在knockout.js中格式化括号中的负数

时间:2014-08-15 19:11:37

标签: jquery knockout.js knockout-mapping-plugin

如何格式化负百分比并使用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,") ;
    });

如何修改此功能以检查值是否为负数,例如:-23.44并更改为(23.44)

1 个答案:

答案 0 :(得分:0)

如果您仍然需要它,我认为以下内容应该有效:

...
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,") + ')';
...