0

I have a simple text box and I am entering number value to this.And i want to format the number value to two decimal places and commas at appropriate place.Like If i enter the 10 in the text box and after pressing entering or leaving textbox it should be converted into 10.00. and if i enter 1000 in the textbox and after pressing or entering it should be converted into 1,000.00 Please tell me if there exist any possibility to do this using javascript

<input type="text" name="one" class="currency">
<script>
 $('.currency').live('keydown', function(e) { 
    var key = e.keyCode || e.which; 

      if (key== 9 || key == 13) { 
        e.preventDefault(); 
          if( isNaN( parseFloat( this.value ) ) ) return;
                this.value = parseFloat(this.value).toFixed(2);
        // call custom function here
      }         

});
</script>

This code will return output as 1000.00 But i need period and commas in their appropriate place

Lance
  • 4,736
  • 16
  • 53
  • 90
Nimesh
  • 100
  • 9
  • Do you want a solution for PHP (use [`number_format`](http://php.net/manual/en/function.number-format.php)) or JS? ... make your mind up – naththedeveloper Oct 04 '13 at 07:12
  • See [Javascript: Easier way to format numbers?](http://stackoverflow.com/questions/726144/javascript-easier-way-to-format-numbers) for a jQuery solution. – naththedeveloper Oct 04 '13 at 07:15

3 Answers3

4
var price = 34523453.345
price.toLocaleString()

O/P "34,523,453.345"
0

You can use numeral.js (http://numeraljs.com/) to do the job.

Example code:

var string = numeral(1000).format('0,0.00');
// output is 1,000.00
Chokchai
  • 1,684
  • 12
  • 12
0

Something like this should do it:

<script type="text/javascript">
function makeCurrency(val){
    val = parseFloat(val).toFixed(2);
    while (/(\d+)(\d{3})/.test(val.toString())){
        val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
    }
    return val;
}
alert(makeCurrency(12743.7512)); // 12,743.75
alert(makeCurrency(12743)); // 12,743.00
alert(makeCurrency(12743.7)); // 12,743.70
alert(makeCurrency(1274340984893.1)); // 1,274,340,984,893.10
</script>

So you can just copy the function and replace this.value = parseFloat(this.value).toFixed(2); with this.value = makeCurrency(this.value);

Originally from add commas to a number in jQuery

Community
  • 1
  • 1
jxmallett
  • 4,087
  • 1
  • 28
  • 35