Skip to content

Instantly share code, notes, and snippets.

@nimolix
Created December 26, 2012 18:30
Show Gist options
  • Save nimolix/4382065 to your computer and use it in GitHub Desktop.
Save nimolix/4382065 to your computer and use it in GitHub Desktop.
Convert a numeric value into Persian words
String.prototype.persianThousandsSeparator = function () {
var val = this.toString();
var x = val.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '٬' + '$2');
}
return x1 + x2;
};
String.prototype.toPersianWords = function() {
var val = this.toString();
var suf = ['هزار', 'میلیون', 'میلیارد', 'تیریلیون'];
var n = ['یک', 'دو', 'سه', 'چهار', 'پنج', 'شش', 'هفت', 'هشت', 'نه'];
var n1 = ['ده', 'یازده', 'دوازده', 'سیزده', 'چهارده', 'پانزده', 'شانزده', 'هفده', 'هجده', 'نوزده'];
var n2 = ['بیست', 'سی', 'چهل', 'پنجاه', 'شصت', 'هفتاد', 'هشتاد', 'نود'];
var n3 = ['صد', 'دویست', 'سیصد', 'چهارصد', 'پانصد', 'ششصد', 'هفتصد', 'هشتصد', 'نهصد'];
if (s == '0') {
return 'صفر';
}
var num = val.persianThousandsSeparator().split('٬');
var thousand = num.length;
var str = '';
for (i in num) {
var part = num[i];
var comp = [];
while (part.length < 3) {
part = '0' + part;
}
var y = parseInt(part.charAt(0));
var d = parseInt(part.charAt(1));
var s = parseInt(part.charAt(2));
if (n3[y - 1]) {
comp.push(n3[y - 1]);
}
if (d == 1) {
comp.push(n1[s] + ' ');
} else {
if (n2[d - 2]) {
comp.push(n2[d - 2]);
}
if (n[s - 1]) {
comp.push(n[s - 1]);
}
}
str += comp.join(' و ');
if (comp.length && suf[thousand - 2]) {
str += ' ' + suf[thousand - 2] + ' و ';
}
thousand--;
}
return str.replace(/ و $/g, '');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment