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

I do not need a mask, but I need something that will format currency(in all browsers) and not allow for any letters or special char's to be typed. Thanks for the help

Example:

Valid: $50.00
$1,000.53

Not Valid: $w45.00
$34.3r6

This question is related to jquery currency formatter

The answer is


As a corollary to why the jQuery FormatCurrency plugin is a good answer, I'd like to rebut your comment:

1. code.google.com/p/jquery-formatcurrency - Does not filter out all letter's. You can type a single letter and it will not remove it.

Yes, formatCurrency() by itself does not filter out letters:

// only formats currency
$(selector).formatCurrency();

But toNumber(), included in the formatCurrency plugin, does.

You thus want to do:

// removes invalid characters, then formats currency
$(selector).toNumber().formatCurrency();

Try regexp currency with jQuery (no plugin):

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('#test').click(function() {_x000D_
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);_x000D_
    if (TESTCURRENCY.length <= 1) {_x000D_
      $('#valueshow').val(_x000D_
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))_x000D_
      );_x000D_
    } else {_x000D_
      $('#valueshow').val('Invalid a value!');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="text" value="12345.67890" id="value">_x000D_
<input type="button" id="test" value="CLICK">_x000D_
<input type="text" value="" id="valueshow">
_x000D_
_x000D_
_x000D_

Edit: New check a value to valid/invalid


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();
}

Use jquery.inputmask 3.x. See demos here

Include files:

<script src="/assets/jquery.inputmask.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.extensions.js" type="text/javascript"></script>
<script src="/assets/jquery.inputmask.numeric.extensions.js" type="text/javascript"></script>

And code as

$(selector).inputmask('decimal',
  { 'alias': 'numeric',
    'groupSeparator': '.',
    'autoGroup': true,
    'digits': 2,
    'radixPoint': ",",
    'digitsOptional': false,
    'allowMinus': false,
    'prefix': '$ ',
    'placeholder': '0'
  }
);

Highlights:

  • easy to use
  • optional parts anywere in the mask
  • possibility to define aliases which hide complexity
  • date / datetime masks
  • numeric masks
  • lots of callbacks
  • non-greedy masks
  • many features can be enabled/disabled/configured by options
  • supports readonly/disabled/dir="rtl" attributes
  • support data-inputmask attribute(s)
  • multi-mask support
  • regex-mask support
  • dynamic-mask support
  • preprocessing-mask support
  • value formatting / validating without input element

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());

I used to use the jquery format currency plugin, but it has been very buggy recently. I only need formatting for USD/CAD, so I wrote my own automatic formatting.

$(".currencyMask").change(function () {
            if (!$.isNumeric($(this).val()))
                $(this).val('0').trigger('change');

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

Simply set the class of whatever input should be formatted as currency <input type="text" class="currencyMask" /> and it will format it perfectly in any browser.