Linesofcode
Linesofcode

Reputation: 5903

Sum currency with comma and dot

My code is working if the separator of decimals is a comma, but the user can choose between dot and comma.

The problem I'm facing is showing the total well formated (with two decimal places; formated by the separator of decimals; and with the separator of thousands as well)

$('#mytable').dataTable(
{
    'footerCallback': function ( row, data, start, end, display )
    {
        var api = this.api();

        // Remove the formatting to get integer data for summation
        var intVal = function ( i ) {
            return typeof i === 'string' ? i.replace(/[\$,]/g, '') * 1 : typeof i === 'number' ? i : 0;
        };

        var total  = api.column(3).data()
                                  .reduce( function (a, b) 
                                  {
                                    return intVal(a) + intVal(b);
                                  }, 0);

        $('#total').text(parseFloat(total).toFixed(2).replace(/(\d)(?=(\d{3})+\,)/g, '$1,'));
    }
});

You can check the problem directly in JSFiddle.

enter image description here

Upvotes: 1

Views: 4049

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386680

You can use a build in function for localisation of numbers:

var number = 9876543.2109;
document.write(number.toLocaleString('en-US', { maximumFractionDigits: 2 }));
document.write('<br>');
document.write(number.toLocaleString('de-DE', { maximumFractionDigits: 2 }));

Upvotes: 2

Justinas
Justinas

Reputation: 43507

Take number in any format (assuming it's always with 2 decimal numbers), remove any non-numerical symbols, divide it by 100 and you have your pure integer:

function test() {
  var a = parseInt($('#a').val().replace(/[^0-9]/g, '')) / 100;
  var b = parseInt($('#b').val().replace(/[^0-9]/g, '')) / 100;
  $("#result").text(a + b);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a" placeholder="1, 455.00" />+
<input type="text" id="b" placeholder="1 Thousand 1 hundred 50 and 50 cents" />=
<span id="result">???</span>
<hr/>
<button onClick="test()">Calculate</button>

Upvotes: 2

Related Questions