JQuery Number Formatting
Asked Answered
H

8

54

There are way too many questions and answers about this basic functionality, I cannot see the wood for the trees.

In Java there is only one simple answer (java.text.NumberFormat and its subclasses) so I'm sure the majority of plugins, questions and answers will mature eventually to a de-facto standard for JQuery.

This plugin is the best I found so far, but I don't know if it's still developed, is mature etc.

http://plugins.jquery.com/project/numberformatter

Is there a better solution? Is it mature / active enough to rely on?


Edit:

I would like to be able to format currencies, decimal, integers based on the same format patterns Java uses, so that data recieved on the client side can be formatted without sending it first to the server.

e.g.

Format 1000 to $1,000 or 1,000.00 etc (locale support is nice)

Seems that http://plugins.jquery.com/project/numberformatter does the job but the question was: "Am I using the right thing?" or "Is there a better way to do so?"

Heffernan answered 6/9, 2011 at 22:47 Comment(7)
Is this a rant or a question?Willi
for the record Java and Javascript are two entirely different things. It's not really fair to knock js or jQuery for not having a java feature :PZippy
@Willi - a question, the ranting is a side effect, sorryHeffernan
@Joseph - I got used to find a solution to anything JQuery, I got spoiled...Heffernan
A more reasonable question would be to state your formatting requirements so that suggestions can be made on how to best meet them. Loading a library and associated plugin simply to get formatting for money, for example, is way overkill when a function of two or three lines will do the job. On the other hand, if you are looking for something that will "do everything" then likely you haven't spent enough time working out what your requirements are.Fungal
autoNumeric does the job: decorplanit.com/pluginHoltorf
Broken link. Can you please update.Unreality
K
85

I would recommend looking at this article on how to use javascript to handle basic formatting:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

source: http://www.mredkj.com/javascript/numberFormat.html

While jQuery can make your life easier in a million different ways I would say it's overkill for this. Keep in mind that jQuery can be fairly large and your user's browser needs to download it when you use it on a page.

When ever using jQuery you should step back and ask if it contributes enough to justify the extra overhead of downloading the library.

If you need some sort of advanced formatting (like the localization stuff in the plugin you linked), or you are already including jQuery it might be worth looking at a jQuery plugin.

Side note - check this out if you want to get a chuckle about the over use of jQuery.

Kovrov answered 6/9, 2011 at 23:13 Comment(4)
I've made a jQuery Plug-in with this code. Now it's easy to apply to multiple places in a page: $('.number').formatNumber();. Default is make 1343034.09 into 1,343,034.09 - github.com/RaphaelDDL/jquery.formatNumberAreca
Abe, the link you provide is extremely helpful. Perhaps you could edit your answer and add the main functions here in case it disappears? You're already given proper credit.Mcdaniels
Not a bad idea @PerryTew - addedKovrov
old answer but works out of the box, just by copy and paste, great!!!Druse
C
24

Using the jQuery Number Format plugin, you can get a formatted number in one of three ways:

// Return as a string
$.number( 1234.5678, 2 ); // Returns '1,234.57'

// Place formatted number directly in an element:
$('#mynum').number( 1234.5678 ); // #mynum would then contain '1,235'

// Replace existing number values in any element
$('span.num').number( true, 2 ); // Formats and replaces existing numbers in those elements.

If you don't like the format, or you need to localise, there are other parameters that let you choose how the number gets formatted:

.number( theNumber, decimalPlaces, decimalSeparator, thousandsSeparator )

You can also get jQuery Number Format from GitHub.

Clockmaker answered 28/10, 2012 at 21:29 Comment(2)
Including an external reference to a well documented source is appreciated here on Stack Overflow but it is important to include in your answer the most important/relevant snippets from the external source and give context as to how the answer the question.Taunton
I was using this plugin for a while and it's not usable. When you type you sew how values are formated with delay. Cursor jumps, so If you enter field and you have 0 in it, you selected it and start to type 220 cusor jumps and you get 202 etc.. realy bad if you want to do pro pages.Donn
A
13

Browser development progresses:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

 Number.toLocaleString(locale);

 // E.g.
 parseFloat("1234567.891").toLocaleString(window.document.documentElement.lang);
 "1,234,567.891"
Ahouh answered 27/8, 2018 at 16:42 Comment(3)
That does not work for Spanish locales and number < 10,000Ogham
Works for me: parseFloat("1234.891").toLocaleString('es-ES'); outputs "1234,891". It appears correct as both - with full-stop and without - are permitted for es-ES. If you require '.' then use ca-ES locale that does have it.Ahouh
That was what I was talking about. Thousands separator does not work for numbers less than 10,000 in Spanish locales, but nevermind, I have created a jquery extension method with only one line of code in order to format an integer with thousands separator without needing to worry about setting a particular culture.Ogham
G
7

I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }

For example:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56
Gordon answered 23/7, 2018 at 18:19 Comment(0)
H
3

If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric. Works a treat. Have been using it successfully for several years now.

Holtorf answered 7/6, 2016 at 8:42 Comment(0)
F
2

Putting this http://www.mredkj.com/javascript/numberFormat.html and $('.number').formatNumber(); concept together, you may use the following line of code;

e.g. <td class="number">1172907.50</td> will be formatted like <td class="number">1,172,907.50</td>

$('.number').text(function () { 
    var str = $(this).html() + ''; 
    x = str.split('.'); 
    x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
        x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
    } 
    $(this).html(x1 + x2); 
});
Femoral answered 11/6, 2014 at 5:26 Comment(0)
B
1

http://jquerypriceformat.com/#examples

https://github.com/flaviosilveira/Jquery-Price-Format

html input runing for live chance.

<input type="text" name="v7"  class="priceformat"/>
<input type="text" name="v8"  class="priceformat"/>


$('.priceformat').each(function( index ) {
    $(this).priceFormat({ prefix: '',  thousandsSeparator: '' });
});

//5000.00

//5.000,00

//5,000.00

Burgomaster answered 22/10, 2014 at 15:32 Comment(0)
B
0

http://locutus.io/php/strings/number_format/

module.exports = function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-enter code hereline camelcase
  //  discuss at: http://locutus.io/php/number_format/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // improved by: davook
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Theriault (https://github.com/Theriault)
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Michael White (http://getsprink.com)
  // bugfixed by: Benjamin Lupton
  // bugfixed by: Allan Jensen (http://www.winternet.no)
  // bugfixed by: Howard Yeend
  // bugfixed by: Diogo Resende
  // bugfixed by: Rival
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  //  revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  //  revised by: Luke Smith (http://lucassmith.name)
  //    input by: Kheang Hok Chin (http://www.distantia.ca/)
  //    input by: Jay Klehr
  //    input by: Amir Habibi (http://www.residence-mixte.com/)
  //    input by: Amirouche
  //   example 1: number_format(1234.56)
  //   returns 1: '1,235'
  //   example 2: number_format(1234.56, 2, ',', ' ')
  //   returns 2: '1 234,56'
  //   example 3: number_format(1234.5678, 2, '.', '')
  //   returns 3: '1234.57'
  //   example 4: number_format(67, 2, ',', '.')
  //   returns 4: '67,00'
  //   example 5: number_format(1000)
  //   returns 5: '1,000'
  //   example 6: number_format(67.311, 2)
  //   returns 6: '67.31'
  //   example 7: number_format(1000.55, 1)
  //   returns 7: '1,000.6'
  //   example 8: number_format(67000, 5, ',', '.')
  //   returns 8: '67.000,00000'
  //   example 9: number_format(0.9, 0)
  //   returns 9: '1'
  //  example 10: number_format('1.20', 2)
  //  returns 10: '1.20'
  //  example 11: number_format('1.20', 4)
  //  returns 11: '1.2000'
  //  example 12: number_format('1.2000', 3)
  //  returns 12: '1.200'
  //  example 13: number_format('1 000,50', 2, '.', ' ')
  //  returns 13: '100 050.00'
  //  example 14: number_format(1e-8, 8, '.', '')
  //  returns 14: '0.00000001'

  number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number
  var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  var s = ''

  var toFixedFix = function (n, prec) {
    if (('' + n).indexOf('e') === -1) {
      return +(Math.round(n + 'e+' + prec) + 'e-' + prec)
    } else {
      var arr = ('' + n).split('e')
      var sig = ''
      if (+arr[1] + prec > 0) {
        sig = '+'
      }
      return (+(Math.round(+arr[0] + 'e' + sig + (+arr[1] + prec)) + 'e-' + prec)).toFixed(prec)
    }
  }

  // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec).toString() : '' + Math.round(n)).split('.')
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }

  return s.join(dec)
}
Binary answered 27/1, 2019 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.