Numbers thousands Grouping/Separating and formating
https://stackoverflow.com/a/58136480/7514010
by PAPIONbit
HTML
<h3>
Numbers thousands Grouping/Separating and formating
</h3>
Universal, fast, accurate, simple function
<ul>
<li>Using RegEx (Fast & Accurate)</li>
<li>Support Numbers(Float/Integer)/String/Multiple numbers in a string</li>
<li>Smart well (Not grouping decimals - Compatible with different types of grouping)</li>
<li>Support all browsers specially 'Safari' & 'IE' & many older browsers</li>
<li>[Optional] Respecting non-English (Persian/Arabic) digits (+ Pre-fix)</li>
</ul>
<input id="test" placeholder="Type any number here" oninput="document.getElementById('result').innerHTML=formatNums(this.value)">
<div>
Result:
<div id="result"></div>
</div>
<br><a href="https://stackoverflow.com/a/58136480/7514010">More information</a>
JavaScript
var text='100000000 English or Persian/Arabic ۱۲۳۴۵۶۷۸۹/٠١٢٣٤٥٦٧٨٩ this is 123123123.123123123 with this -123123 and these 10 100 1000 123123/123123 (2000000) .33333 100.00 or any like 500000Kg',
numInt=10000000,
numFloat=10000000.0022,
str='10000000.2200';
// num: Number/s (String/Number),
// sep: Thousands separator (String) - Default: ','
// dec: Decimal separator (String) - Default: '.' (Just one char)
// u: Universal support for languages characters (String - RegEx character set / class) - Example: '[\\d\\u0660-\\u0669\\u06f0-\\u06f9]' (English/Persian/Arabic), Default: '\\d' (English)
function formatNums(num,sep,dec,u) {
// Setting defaults
sep=sep||','; // Seperator
u=u||'\\d'; // Universal character set \d: 0-9 (English)
// Mixing of Handeling numbers when the decimal character should be changed + Being sure the input is string
if(typeof num!='string') {
num=String(num);
if( dec && dec!='.') num=num.replace('.',dec); // Replacing sure decimal character with the custom
}
//
return num.replace(RegExp('\\'+(dec||'.')+u+'+|'+u+'(?=(?:'+u+'{3})+(?!'+u+'))','g'),
// The RegEx will be like /\.\d+|\d(?=(?:\d{3})+(?!\d))/g if not be customized
// RegEx explain:
// 1) \.\d+ : First try to get any part that started with a dot and followed by any much of English digits, one or more (For ignoring it later)
// 2) | : Or
// 3) \d : Get any 1 char digit
// 3.1) (?=...) : That the next of that should be
// 3.2) (?:\d{3}) : 3 length digits
// 3.2.1) + : One or more of the group
// 3.3) (?!\d) : ...till any place that there is no digits
function(a) { // Any match can be the decimal part or the integer part so lets check it
return a.length==1 ? a+sep : a // If the match is...