How can I correctly format currency using jquery? How can I correctly format currency using jquery? jquery jquery

How can I correctly format currency using jquery?


Another option (If you are using ASP.Net razor view) is, On your view you can do

<div>@String.Format("{0:C}", Model.total)</div>

This would format it correctly. note (item.total is double/decimal)

if in jQuery you can also use Regex

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


Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

function formatCurrency(total) {    var neg = false;    if(total < 0) {        neg = true;        total = Math.abs(total);    }    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();}