1

I want to display the dollar timer which goes from 1 to 2500. When the timer increases to 1000, I want to display it as $1,000 instead of $1000. I want commas in thousands place.Could someone help me with this JavaScript.

Thanks.

user2524653
  • 108
  • 7

3 Answers3

0

You could easily do this with a regular expression.

var friendlyNum = (num + "").replace(/^(\d)(\d{3})$/, "$1,$2");

Note that this will only handle 1000 places.

How it works is an exercise to the reader. For learning how they work, stat here.

alex
  • 479,566
  • 201
  • 878
  • 984
0

Even though it's been written a thousand times, I felt like writing some JS.

var addCommas = function(number) {
    number = '' + number;

    var negative = false;
    if (number.match(/^\-/)) {
        negative = true;
    }

    number = number.replace(/[^0-9\.]/g, '');
    number = number.split('.');

    var before = number.shift()
        , after = number.join('');

    for (var i = (before.length - 3); i > 0; i -= 3) {
        before = before.substr(0, i) + ',' + before.substr(i)
    }

    return (negative ? '-' : '') + before + (after ? '.' + after : '');
}

// 1,000.00
addCommas(1000.00);
// -1,234,567,890
addCommas('-1234567890');
ZachRabbit
  • 5,144
  • 1
  • 23
  • 16
0

Below is the approach to convert number format (comma separated)

HTML :-

         <input type="text" onkeyup="convertNumberFormat(this.value)" />

JavaScript:-

function convertNumberFormat(inputValue)
   {
    inputValue = inputValue.toString();
    inputValue = inputValue.replace( /\,/g, "");
    var x = inputValue.split( '.' );
    var intValue = x[0];
    var floatValue = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while ( rgx.test(intValue) ) {
        intValue = intValue.replace( rgx, '$1' + ',' + '$2' );
    }
    alert(intValue + floatValue);
}

In HTML template I am calling this function at "onkeyup" event. you just need to call "convertNumberFormat" function whenever you want to validate your input value and pass current inserted value...

Example:-

       convertNumberFormat('$2500');

Output:-

       '$2,500' // in alert.

hope this can help you...

Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42