Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate thousands while typing in Farsi (Persian)

I'm using this snippet to separate thousands inside input field while user is typing. It works correctly with English (Latin) 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">
like image 331
mdehghani Avatar asked Oct 18 '25 16:10

mdehghani


1 Answers

This code is for Iranians. This code inserts the thousands separator after converting the number to Persian.

function insertRialComma(n) {
    let m = "";
    for (let i = 0; i < n.length; i++) {
        let c = n.substring(n.length - i - 1, n.length - i);
        if (i % 3 === 0 && i > 0) {
            m = c + "٬" + m; // Persian/Arabic thousands separator
        } else {
            m = c + m;
        }
    }
    return m;
}

function toFarsiNumber(n) {
    n = n.toString();
    let o = "";
    const farsiDigits = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
    const englishDigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    for (let i = 0; i < n.length; i++) {
        for (let j = 0; j < englishDigits.length; j++) {
            if (n.substring(i, i + 1) === englishDigits[j]) {
                o = o + farsiDigits[j];
            }
        }
    }
    return o;
}

let n = insertRialComma(toFarsiNumber("1222345"));
alert(n);
like image 161
R. Yaghoobi Avatar answered Oct 20 '25 05:10

R. Yaghoobi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!