0

I would like to format amount on keyup javascript event. I need a result like this:

  • 100 > 100
  • 1000 > 1 000
  • 100000000 > 100 000 000
  • 1000,12 > 1 000,12

Can you help me please?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
ucf
  • 21
  • 1
  • 2
  • 7
  • i tried thos function that i have found in the stackoverflow site, http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript but the result was NaN – ucf Nov 30 '12 at 21:18
  • 1
    jquery, keyup, trim :) these are the keywords to get you going, since I don't think anyone, including me, will bother with the full answer. – povilasp Nov 30 '12 at 21:24
  • Is this a question about formatting, a question about event handling? You said you tried the other answer. Exactly what did you try? Did you make any changes to adapt to your situation? Have you tried anything else besides a copy of another answer? Is a jQuery solution ok, or do you require pure JavaScript? – lurker Jul 10 '19 at 10:08

3 Answers3

0

You need something like this:

function formatNumber(numberString) {
    var commaIndex = numberString.indexOf(',');
    var int = numberString;
    var frac = '';

    if (~commaIndex) {
        int = numberString.slice(0, commaIndex);
        frac = ',' + numberString.slice(commaIndex + 1);
    }

    var firstSpanLength = int.length % 3;
    var firstSpan = int.slice(0, firstSpanLength);
    var result = [];

    if (firstSpan) {
        result.push(firstSpan);
    }

    int = int.slice(firstSpanLength);

    var restSpans = int.match(/\d{3}/g);

    if (restSpans) {
        result = result.concat(restSpans);
        return result.join(' ') + frac;
    }

    return firstSpan + frac;
}

formatNumber('1234567890,12'); // "1 234 567 890,12"

Use it with your event listener and send to this function strings that represents numbers and it will return strings int the desired format

input.onkeyup = function () {
    input.value = input.value.replace(/\d+(?:,\d+)?/g, formatNumber);
};
micnic
  • 10,915
  • 5
  • 44
  • 55
0
function formatNumberField() {
    // unformat the value
    var value = this.value.replace(/[^\d,]/g, '');

    // split value into (leading digits, 3*x digits, decimal part)
    // also allows numbers like ',5'; if you don't want that,
    // use /^(\d{1,3})((?:\d{3})*))((?:,\d*)?)$/ instead
    var matches = /^(?:(\d{1,3})?((?:\d{3})*))((?:,\d*)?)$/.exec(value);

    if (!matches) {
        // invalid format; deal with it however you want to
        // this just stops trying to reformat the value
        return;
    }

    // add a space before every group of three digits
    var spaceified = matches[2].replace(/(\d{3})/g, ' $1');

    // now splice it all back together
    this.value = [matches[1], spaceified, matches[3]].join('');
}

// attaching event handler with jQuery...
$(document).ready(function() {
    $('#your-element-id').on('keyup', formatNumberField);
});

// With vanilla JS, it can get a little ugly.  This is the simplest way that
// will work in pretty much all browsers.
// Stick this in your "dom is loaded" callback
document.getElementById('your-element-id').onkeyup = formatNumberField;
cHao
  • 84,970
  • 20
  • 145
  • 172
  • @whitebox: Oops. I'd tested the regex, but not the whole thing together. Should work now. – cHao Jul 14 '15 at 01:25
  • It does not allow .00 and allows multiple ',' – Banty Roy Nov 21 '16 at 13:53
  • @BantyRoy: This code was not intended to pay attention to `.`. You might have noticed, the format of the numbers is different. `,` is the decimal point in this case, which generally means . is the thousands separator. – cHao Nov 22 '16 at 01:01
0

Here's a wacky format function that was fun to think about:

function formatNumber(s) {
  var parts = s.split(/,/)
    , spaced = parts[0]
         .split('').reverse().join('') // Reverse the string.
         .match(/\d{1,3}/g).join(' ') // Join groups of 3 digits with spaces.
         .split('').reverse().join(''); // Reverse it back.
  return spaced + (parts[1] ? ','+parts[1] : ''); // Add the fractional part.
}

You can attach it to an element's "keyup" event by using element.addEventListener(...) in pure JavaScript or the .on(...) function in jQuery, e.g.:

$('.my-input').on('keyup', function() {
  var $this = $(this);
  $this.val(formatNumber($this.val());
});
maerics
  • 151,642
  • 46
  • 269
  • 291