c85a6685425ca25d038947839efceadabd803915
[platform/framework/web/crosswalk-tizen.git] /
1 var toNumber = require('../lang/toNumber');
2
3     /**
4      * Converts number into currency format
5      */
6     function currencyFormat(val, nDecimalDigits, decimalSeparator, thousandsSeparator) {
7         val = toNumber(val);
8         nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits;
9         decimalSeparator = decimalSeparator == null? '.' : decimalSeparator;
10         thousandsSeparator = thousandsSeparator == null? ',' : thousandsSeparator;
11
12         //can't use enforce precision since it returns a number and we are
13         //doing a RegExp over the string
14         var fixed = val.toFixed(nDecimalDigits),
15             //separate begin [$1], middle [$2] and decimal digits [$4]
16             parts = new RegExp('^(-?\\d{1,3})((?:\\d{3})+)(\\.(\\d{'+ nDecimalDigits +'}))?$').exec( fixed );
17
18         if(parts){ //val >= 1000 || val <= -1000
19             return parts[1] + parts[2].replace(/\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : '');
20         }else{
21             return fixed.replace('.', decimalSeparator);
22         }
23     }
24
25     module.exports = currencyFormat;
26
27