JavaScript; How to set dot after three digits?

user6771756 picture user6771756 · Mar 24, 2017 · Viewed 10.7k times · Source

I have the following JavaScript code:

var calculation = $('select[name=somevalue1] option:selected').data('calc')-($('select[name=somevalue1] option:selected').data('calc')/100*$('select[name=somevalue2] option:selected').data('calc'))-($('select[name=somevalue1] option:selected').data('calc')-($('select[name=somevalue1] option:selected').data('calc')/100*$('select[name=somevalue2] option:selected').data('calc')))/100*$('select[name=somevalue3] option:selected').data('calc');

$('#calculation').text((calculation).toFixed(2).replace(".",","))

That will calculate a number, change . to , and round it to two digits after comma.

What I need to do is to add a dot after tree digits before come.

Means:

1.234,56 instead of 1234,56

1.234.567,89 instead of 1234567,89

Does anybody know a way to do that?

Answer

user6771756 picture user6771756 · Mar 24, 2017

This code worked for me:

<p id="calculation"></p>

<script>
    function numberWithCommas(x) {
        var parts = x.toString().split(".");
        parts[0]=parts[0].replace(/\B(?=(\d{3})+(?!\d))/g,".");
        return parts.join(",");
        }

        var calculation = 1231739216.34367;

        document.getElementById("calculation").innerHTML = numberWithCommas((calculation).toFixed(2))
</script>

This code will:

  1. Round (for business) to two digits after dezimal.
  2. Change the decimal dot to comma.
  3. Set a dot every third digit before decimal.