I have a function that sums a column of data in an html table. It does so admirably only I would like to have it put the commas in there that are needed to separate the thou
I got somewhere with the following method:
var value = 123456789.9876543 // i.e. some decimal number
var num2 = value.toString().split('.');
var thousands = num2[0].split('').reverse().join('').match(/.{1,3}/g).join(',');
var decimals = (num2[1]) ? '.'+num2[1] : '';
var answer = thousands.split('').reverse().join('')+decimals;
Using split-reverse-join is a sneaky way of working from the back of the string to the front, in groups of 3. There may be an easier way to do that, but it felt intuitive.
best and simple way to format the number is to use java-script function
var numberToformat = 1000000000
//add locality here, eg: if you need English currency add 'en' and if you need Danish currency format then use 'da-DA'.
var locality = 'en-EN';
numberToformat = numberToformat.toLocaleString(locality , {
minimumFractionDigits: 4 })
document.write(numberToformat);
for more information click documentation page
Consider this:
function group1k(s) {
return (""+s)
.replace(/(\d+)(\d{3})(\d{3})$/ ,"$1 $2 $3" )
.replace(/(\d+)(\d{3})$/ ,"$1 $2" )
.replace(/(\d+)(\d{3})(\d{3})\./ ,"$1 $2 $3.")
.replace(/(\d+)(\d{3})\./ ,"$1 $2." )
;
}
It's a quick solution for anything under 999.999.999, which is usually enough. I know the drawbacks and I'm not saying this is the ultimate weapon - but it's just as fast as the others above and I find this one more readable. If you don't need decimals you can simplify it even more:
function group1k(s) {
return (""+s)
.replace(/(\d+)(\d{3})(\d{3})$/ ,"$1 $2 $3")
.replace(/(\d+)(\d{3})$/ ,"$1 $2" )
;
}
Isn't it handy.
<script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
Use:
numberWithCommas(200000);
==> 200,000
I know this is an uber old post and has good answers, BUT if anyone is interested, there is a jQuery plugin which simplifies number formatting (thousands formatting, number of decimal places, custom thousands separator, etc) by making an include and a simple call. Has lots of features and documentation is enough. It's called jQuery Number.
You just include it:
<script type="text/javascript" src="jquery/jquery.number.min.js"></script>
And then use it:
On an automatic formatting HTML input: $('input.number').number( true, 2 );
or
On a JS call: $.number( 5020.2364, 2 ); // Outputs: 5,020.24
Hopefully this helps someone.
Seems like this is ought to be the approved answer...
Intl.NumberFormat('en-US').format(count)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat