Cara JQUERY Merubah Text jadi Format Nomor

Jika anda menggunakan jquery dan mendapati kasus ingin merubah text di input text menjadi format number dimana ada penanda titik atau koma pada setiap angka ribuan maka gunakan saja script berikut ini :

(function($){
/**
A quick plugin which implements phpjs.org's number_format as a jQuery
plugin which formats the number, and inserts to the DOM.
/* By Sam Sehnert, teamdf.com — http://www.teamdf.com/web/jquery-number-format/178/ */

$.fn.number = function( number, decimals, dec_point, thousands_sep ){ 
 number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
 var n = !isFinite(+number) ? 0 : +number,
 prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
 sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
 dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
 s = '',
 toFixedFix = function (n, prec) {
 var k = Math.pow(10, prec);
 return '' + Math.round(n * k) / k;
 };
 // Fix for IE parseFloat(0.55).toFixed(0) = 0;
 s = (prec ? toFixedFix(n, prec) : '' + 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');
 }
 // Add this number to the element as text.
 this.text( s.join(dec) );
 };
})(jQuery);

Kemudian cobalah

 

var myNumber = 5000.1;
 $('.number').number( myNumber, 2 ); // 2 decimal places.
// Output: 5,000.10
$('.number').number( myNumber ); // 0 decimal places (rounded).
// Output: 5,000
$('.number').number( myNumber, 1, ',', ' ' );
// Output: 5 000,1

Selesai dan anda telah merubah text berisi nomor ke dalam nomor yang terformat. Selamat mencoba

Sumber : http://www.teamdf.com/web/jquery-number-format/178/

Leave a Reply

Your email address will not be published. Required fields are marked *



*