OL Learn

Formatting float type data - need 2 decimals and comma


#1

For some reason I am having difficulty getting the data formatted the way I need it.

in datamapper - I have it set to ‘float’ - I have this because I am also graphing the data
in template - the zero drops off at end of data ( ex. 5750.50 is returned 5750.5)

I do not want the currency symbol. I have tried this setting but it adds parenthesis when it is a negative number. I need to have the negative sign ( ex. -5750.50)

I used toFixed(2) to get the zeros but I can not get the comma added.

Data examples -
Mapper Template Need
-5750.5 -5750.5 -5,750.50
37860.60 37860.6 37,860.60

Any ideas as to why I am having difficulty?
Thanks


#2

Try something like this:

var field = "123456.78";
var result = parseFloat(field).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
logger.info(result);

// output: 123,456.78

#3

Alternatively one could use the formatter object with a custom pattern.

var theVal = -5750.5;
var formattedVal = formatter.number( theVal, "#,##0.00" );
//output: -5,750.50

The following shows how (for example) negative values can be placed between parentheses.

var theVal = -5750.5;
var formattedVal = formatter.number( theVal, "#,##0.00;(#,##0.00)" );
//output: (5,750.50)