3

i'm using this snippet to separate thousands inside input field while user is typing. it works correctly with English letters but doesn't respond to Farsi(persian) ones. Is there any way to make it compatible?

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if (event.which >= 37 && event.which <= 40) return;

  // format number
  $(this).val(function(index, value) {
    return value
      .replace(/\D/g, "")
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control number" type="text" value="0" name="subjectvalue" id="txt_subjectvalue">
vsync
  • 118,978
  • 58
  • 307
  • 400
mdehghani
  • 504
  • 1
  • 7
  • 23
  • Possible duplicate of [Regex for persian number](https://stackoverflow.com/questions/28123552/regex-for-persian-number) – GalAbra May 13 '18 at 19:27
  • By changing the first replace to: `.replace(/[^\d\u0660-\u0669\u06f0-\u06f9]+/g,'')` and second replace to `.replace(/[\d\u0660-\u0669\u06f0-\u06f9](?=(?:[\d\u0660-\u0669\u06f0-\u06f9]{3})+(?![\d\u0660-\u0669\u06f0-\u06f9]))/g,'$&,')` it will support Persian/Arabic numbers too. Read more about: https://stackoverflow.com/a/58136480/7514010 – MMMahdy-PAPION Jan 06 '22 at 20:12

3 Answers3

2

This code is for Iranians. This code inserts the comma after Persianizing the numbers.

function insertrialcamma( n ) {
        var m = "";
        for ( var i = 0; i < n.length; i++ ) {
            var c = n.substr( n.length - i - 1, 1 );
            if ( i % 3 == 0 & i > 0 ) {
                m = c + ',' + m;
            } else {
                m = c + m;
            }
        }
        return m;
    }
    function toFarsiNumber( n ) {
        var o = "";
        n = n.toString();
        const farsiDigits = [ '۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹' ];
        const englishDigits = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ];
        for ( var i = 0; i < n.length; i++ ) {
            for ( var j = 0; j < englishDigits.length; j++ ) {
                if ( n.substr( i, 1 ) == englishDigits[ j ] ) {
                    o = o + farsiDigits[ j ];
                }
            }
        }
        return o;
    }
    var n = insertrialcamma(toFarsiNumber( '1222345' ));
    alert( n )
R. Yaghoobi
  • 459
  • 4
  • 5
0

You can use something like Cleave.js to format your input.

Update:

There are many libraries and plugins for it. even you can do it with pure js, Here is an answer that can help you.

As the Mood mentioned in his answer, you can use the replace() method to do it like below:

var fnf = document.getElementById("formattedNumberField");
fnf.addEventListener('keyup', function(evt){
    var n = parseInt(this.value.replace(/\D/g,''),10);
    fnf.value = n.toLocaleString();
}, false);
Behnam Azimi
  • 2,260
  • 3
  • 34
  • 52
  • 2
    [Are answers that just contain links elsewhere really “good answers”?](https://meta.stackexchange.com/a/8259) – GalAbra May 13 '18 at 19:25
0

This code will grab any value the input element currently has, remove all the , and . characters and convert the String into a Number using toLocaleString() which accepts a language parameter:

// listens to an "input" event on the <input> element
document.querySelectorAll('input')[0].addEventListener('input', onInput_Arabic);
document.querySelectorAll('input')[1].addEventListener('input', onInput_normal);

function onInput_normal(){
   // convert into a Number & cleanup the input's value 
   var v = +(this.value.replace(/[,|\.|\D]/g,''));
   // replace the input's value with the formatted wanted value
   this.value =  this.value ? v.toLocaleString() : '';
}

function onInput_Arabic(){
   // convert into a Number & cleanup the input's value 
   // var v = +(this.value.replace(/[,|\.|\D]/g,''));
   var v = transformNumbers.toEnglish( this.value );
   // replace the input's value with the formatted wanted value
   this.value =  this.value ? (+v).toLocaleString('ar-EG') : '';
}

// transforms Numerals from one language system to another
var transformNumbers = (function(){
    var numerals = {
        persian : ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
        arabic  : ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
    };

    function fromEnglish(str, lang){
        var i, len = str.length, result = "";

        for( i = 0; i < len; i++ )
            result += numerals[lang][str[i]]; 

        return result;
    }

    return {
        toEnglish : function(str){
            var num, i, len = str.length, result = "";

            for( i = 0; i < len; i++ ){
                num = numerals["persian"].indexOf(str[i]);
                num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
                if( num == -1 ) continue // num = str[i];
                result += num; 
            }
              
            return result;
        },

        toPersian : function(str, lang){
            return fromEnglish(str, "persian");
        },

        toArabic : function(str){
            return fromEnglish(str, "arabic");
        }
    }
})();
input{ width:90%; display:block; padding:5px; margin:1em 0; }
<input placeholder='Type Number in Eastern-Arabic (٢٤٦٦٩٢٤٦٦٩)'>

<input placeholder='Type Number in common language (123456) '>

Check my other answer on how to convert a number String into a "thousands" separated String, and for only allowing numbers in the input, see this answer.

vsync
  • 118,978
  • 58
  • 307
  • 400