83

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

ninjasense
  • 13,756
  • 19
  • 75
  • 92
  • Can you explain why the other ones didnt fit your standards? – Jeff Feb 18 '11 at 17:19
  • 37
    StackOverflow is my search engine for questions like this. The community feedback here allows a much quicker and more accurate picture of what tools and practices are valued. I say, keep these types of questions coming. – Feckmore Jan 28 '13 at 16:12
  • 13
    Got here from Google. – the-nick-wilson Dec 24 '15 at 20:36
  • 3
    This question is the top Google search result for "jquery format currency" – Paul L Jul 28 '16 at 19:31
  • Does this answer your question? [How to format numbers as currency string?](https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-string) – Heretic Monkey Apr 07 '20 at 17:04

9 Answers9

106

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());
Seyed Morteza Mousavi
  • 6,855
  • 8
  • 43
  • 69
Melu
  • 1,835
  • 3
  • 14
  • 13
  • 4
    I didn’t vote this down, but I can’t find `@String.Format` in any HTML or jQuery reference. My guess is it has something to do with server-side HTML generated by ASP.NET. Did the original question reference that? – Nate Dec 03 '13 at 17:41
  • 5
    For anyone wondering in the future, @String.Format is the razor engine for ASP.NET || MVC – Kyle Jan 14 '14 at 19:54
  • 2
    I like the regex. Why .toString() at the end? .replace returns a string. – xr280xr Sep 15 '14 at 20:56
  • 5
    I didn't downvote this either, but it deserves it for giving an MVC Razor solution to a question that didn't mention Razor, MVC, or even ASP.NET, and the answer didn't even state that here's a solution for MVC Razor. – Jonathan Wood Sep 26 '14 at 17:10
  • 1
    This is a great answer, but how do I need to change the regex in order to get a number without any decimal places and without the dollar symbol? eg I'd like 16000000 to be displayed as 16,000,000 – ministe Jan 28 '15 at 09:03
  • 3
    Never mind, I've answered my own question: $(".totalSum").text('$' + parseFloat(value, 10).toFixed(0).replace(/(\d)(?=(?:[0-9]{3})+\b)/gm, "$1,").toString()); – ministe Jan 28 '15 at 09:21
  • 1
    What about if I want to replace the decimal separator for ',' and the others for '.'? – Deise Vicentin Aug 24 '15 at 20:10
  • 1
    After searching everywhere with suggestion of plugins and so on, this one worked perfectly! – NoBullMan Feb 11 '19 at 01:25
50

JQUERY FORMATCURRENCY PLUGIN
http://code.google.com/p/jquery-formatcurrency/

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
40

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();
}
2Yootz
  • 3,971
  • 1
  • 36
  • 31
22

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();
Neptune Systems
  • 376
  • 2
  • 5
16

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
drew010
  • 68,777
  • 11
  • 134
  • 162
Fernando Kosh
  • 3,426
  • 1
  • 34
  • 31
  • after downloading the ZIP (from the web) i found that the *.js file inside the ZIP is having a different file naming convention. I a bit confused.... – gumuruh Jul 02 '17 at 04:27
  • @gumuruh Look into dist/ folder of the ZIP file. The ZIPs into root of extracted folder are of package and does not for use. Attention to the extensions. Load only what you should need. – Fernando Kosh Feb 10 '18 at 22:49
  • @FernandoKosh @drew010 Is it possible to use this for multiple elements on a page? With for example: `$('.price-format').inputmaks()` or `$('.price-format').each(function() { $(this).inputmask() })` – remkovdm Aug 04 '20 at 11:18
  • 1
    @remkovdm It's been a while since I've implemented it now, but yes I believe that was fine. The docs and examples show $(selector) which means it can be a CSS selector like any other jQuery one. So `$('.price-format').inputmask('decimal', { ... });` *should* work. – drew010 Aug 13 '20 at 17:00
10

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.

Greg Snider
  • 143
  • 1
  • 9
4

Try regexp currency with jQuery (no plugin):

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

Edit: New check a value to valid/invalid

KingRider
  • 2,140
  • 25
  • 23
  • What the problem to downvote? This question (Please read https://meta.stackoverflow.com/questions/251758/why-is-stack-overflow-so-negative-of-late is thanks) – KingRider Mar 28 '17 at 17:49
2

JavaScript already has it.

var cur = function (amt) {
    return Intl.NumberFormat('en-US', { style: "currency", currency: "USD" }).format(amt);
};
esenkaya
  • 99
  • 4
  • This should be accepted answer. Most of answers had offered all kind of crap like .NET based solutions. “Simplicity is the ultimate sophistication.” – Leonardo da Vinci – Alex K Jun 14 '23 at 17:19
0

C#

@{
    CultureInfo newCulture = CultureInfo.CreateSpecificCulture(Model.culture);
var ri = new RegionInfo(@newCulture.LCID);
}

jQuery

$(document).find("#labGrandTotal").text(Intl.NumberFormat('@Model.culture', { style: 'currency', currency: '@ri.ISOCurrencySymbol'}).format(num));

Where Model.culture is for example "en-GB"

aegsomweb
  • 83
  • 1
  • 9