rory-h rory-h - 9 months ago 42
HTML Question

Add comma separator to a numbers with 2 decimal points

I've managed to make the user input to 2 decimal points:
enter image description here
Below is my code for two input fields:

$('.ave-daily-accbalance').blur(function(){
var num = parseFloat($(this).val()) || 0;
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);

});

$('.facilitylimit').blur(function(){
var num = parseFloat($(this).val()) || 0;
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);

});


But now I want to seperate the input with comma. So if the user inputs in 500000 - it automatically converts to 500,000.00

Answer Source

You can use Number.prototype.toLocaleString() (documentation) In your case you want to use the second options parameter to specify the number of decimal points you want:

var num = 200000.001231;
var cleanNum = num.toLocaleString('en', {minimumFractionDigits: 2, maximumFractionDigits: 2});
console.log(cleanNum);

Note that the options argument does not work on all browser and versions. If compatibility is key, use num.toLocaleString() with no arguments, and trim/append decimals as needed:

var num = 20000.001231;
var cleanNum = num.toLocaleString('en');
var splitNum = cleanNum.split('.');
if (splitNum.length < 2) {
  // Need to append .00 if num was an integer
  cleanNum = cleanNum + '.00';
} else {
  // Append 0 if there was only 1 decimal, otherwise trim
  // to 2 decimals
  var decimals = splitNum[1];
  decimals = decimals.length < 2 ? decimals + '0' : decimals.slice(0, 2);
  cleanNum = splitNum[0] + '.' + decimals;
}
console.log(cleanNum);

Hope this helps!