Using a Custom Formatter Function

Overview:

Often you would like to manipulate the format of the data in your applications without having to create calculated fields or change the values directly.  In UI5 this is achieved using a formatter function and similar functionality can be achieved using FAB.

An example of this would be appending a percentage sign on to a value for display purposes. 

Instructions:

  1. Add a new Script node to your project if one does not already exist.
  2. Create a new formatter function.

    function myPercentageFormatter(value)
    {
        return value + '%';
    }
  3. Change the Bound Field property to the following:

    path:'/TestValue', formatter:'myPercentageFormatter'

    TestValue: Is the name of the field in the root of the data model.
    myPercentageFormatter: Is the name of the formatter function in JavaScript. 


Another example would be displaying negative numbers surrounded by brackets, similar to Excel.

In the example the Amount field is a Text column in a Table, named DMBTR.

Instructions:

  1. In the Advanced Property of the field DMBTR, set the binding as:
    text="{path : 'DMBTR',type : 'sap.ui.model.type.Float',formatOptions: { groupingEnabled : true, decimals: 2}, formatter: 'amountFormatter'}
  2. In a Script node, create the function 'amountFormatter' as:
function amountFormatter(val) {
	//formats a negative number with brackets (NN.NN)
	if (val !== null) {
	if(parseFloat(val) < 0){
		var newVal = val.replace(/-(?=\d)/,""); //remove minus sign -
		return '(' + newVal + ')';
		}else{
		return val;
		}
	}
}

Another example shows how UI5's built-in number formatters can be used from within a formatter function. In this case, a floating point number has its sign 'reversed', ie formats a positive number as a negative number, and vice-versa.

In the example the Amount field is a floating point number named DMBTR.

Instructions:

  1. In the Advanced Property of the field DMBTR, set the binding as:
    text="{path : 'DMBTR',type : 'sap.ui.model.type.Float',formatOptions: { groupingEnabled : true, decimals: 0}, formatter: 'changeSignFormatter'}
  2. In a Script node, create the function 'changeSignFormatter' as:
function changeSignFormatter(val) {
	//changes a number from a positive to a negative or vice-versa
	if (val !== null) {
		var oFormat = sap.ui.core.format.NumberFormat.getFloatInstance({
			groupingEnabed: true,
			decimals: 0
		});
		var rawVal = oFormat.parse(val);	//takes the given 'string' value float number (eg '-1,234.00') and converts to float
		var newVal = rawVal * -1; 
		return oFormat.format(newVal);
	}
}