Related
I've got a Laravel project but I think I have an idea of how to incorporate the Dynamic Web Twain (https://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx) into it.
The only problem is I'm not quite sure how I would go about adding additional fields to the scanner UI (like what you see here: https://demo.dynamsoft.com/dwt/online_demo_scan.aspx).
At the moment my Laravel site has a working upload portion to a model where I can submit attachments, however, with the attachment form are fields that include "visibility", "type", "upload location" etc. etc. But I can't seem to figure out how I would add fields like what I already use.
From what I've tested, this is an incredibly useful tool and would work well if I could integrate it into all aspects of my site.
The closest thing I can find is here: https://developer.dynamsoft.com/dwt/api-reference/uploading-downloading/sethttpformfield
Which references what is done in this demo: https://demo.dynamsoft.com/Samples/dwt/Scan-Documents-and-Upload-Them/DWT_Scan_Upload_Demo.html
As you can see, you can add a field name and field value, using the "+" button, but I want to add some fields in the form that are available immediately. The other issue that I might need to work around is if I use this demo and add a value and name, this is how everything is posted and I'm not sure how to translate to something my project can understand.
-----------------------------23491353817351
Content-Disposition: form-data; name="This is a field"
Wow
-----------------------------23491353817351
Content-Disposition: form-data; name="RemoteFile"; filename="507-0.jpg"
Content-Type: application/octet-stream
ÿØÿà
This aspect is a necessary part of my project, so unfortunately there's no real way around this besides moving forward.
This is the current script in the online demo:
Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used
var DWObject, blankField = "", extrFieldsCount = 0, upload_returnSth = true;
var CurrentPathName = unescape(location.pathname);
var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
var strHTTPServer = location.hostname;
var strActionPage;
var scriptLanguages = [
{ desc: "PHP", val: "php" },
{ desc: "PHP-MySQL", val: "phpMySQL" },
{ desc: "CSharp", val: "csharp" },
{ desc: "CSharp-MSSQL", val: "csMSSQL" },
{ desc: "VB.NET", val: "vbnet" },
{ desc: "VBNET-MSSQL", val: "vbnetMSSQL" },
{ desc: "JSP", val: "jsp" },
{ desc: "JSP-Oracle", val: "jspOracle" },
{ desc: "ASP", val: "asp" },
{ desc: "ASP-MSSQL", val: "aspMSSQL" },
{ desc: "ColdFusion", val: "cfm" },
{ desc: "CS-Azure", val: "csAzure" }
];
function languageSelected() {
if (document.getElementById("ddlLanguages").selectedIndex > 7)
upload_returnSth = false;
else
upload_returnSth = true;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) == -1) {
document.getElementById("extra-fields-div-id").style.display = 'none';
document.getElementById('div-extra-fields').style.display = 'none';
}
else {
document.getElementById("extra-fields-div-id").style.display = '';
if (document.getElementById('div-extra-fields').children.length > 1 ||
document.getElementById('div-extra-fields').children[0].children[0].value != '') {
document.getElementById('div-extra-fields').style.display = '';
}
}
}
function addAField() {
extrFieldsCount++;
if (extrFieldsCount == 3) {
document.getElementById('div-extra-fields').style.overflowY = 'scroll';
}
if (document.getElementById('div-extra-fields').style.display == "none")
document.getElementById('div-extra-fields').style.display = '';
else {
document.getElementById('div-extra-fields').appendChild(blankField);
blankField = document.getElementsByClassName('div-fields-item')[extrFieldsCount - 1].cloneNode(true);
}
}
function downloadPDFR() {
DCP_DWT_OnClickCloseInstall();
DWObject.Addon.PDF.Download(
CurrentPath + '/Resources/addon/Pdf.zip',
function () {/*console.log('PDF dll is installed');*/
},
function (errorCode, errorString) {
console.log(errorString);
}
);
}
function Dynamsoft_OnReady() {
blankField = document.getElementsByClassName('div-fields-item')[0].cloneNode(true);
DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
if (DWObject) {
DWObject.Width = 505;
DWObject.Height = 600;
for (var i = 0; i < scriptLanguages.length; i++)
document.getElementById("ddlLanguages").options.add(new Option(scriptLanguages[i].desc, i));
document.getElementById("ddlLanguages").options.selectedIndex = 2;
/*
* Make sure the PDF Rasterizer and OCR add-on are already installedsample
*/
if (!Dynamsoft.Lib.env.bMac) {
var localPDFRVersion = '';
if(Dynamsoft.Lib.product.bChromeEdition){
localPDFRVersion = DWObject._innerFun('GetAddOnVersion', '["pdf"]');
}
else {
localPDFRVersion = DWObject.getSWebTwain().GetAddonVersion("pdf");
}
if (localPDFRVersion != Dynamsoft.PdfVersion) {
var ObjString = [];
ObjString.push('<div class="p15" id="pdfr-install-dlg">');
ObjString.push('The <strong>PDF Rasterizer</strong> is not installed on this PC<br />Please click the button below to get it installed');
ObjString.push('<p class="tc mt15 mb15"><input type="button" value="Install PDF Rasterizer" onclick="downloadPDFR();" class="btn lgBtn bgBlue" /><hr></p>');
ObjString.push('<i><strong>The installation is a one-time process</strong> <br />It might take some time depending on your network.</i>');
ObjString.push('</div>');
Dynamsoft.WebTwainEnv.ShowDialog(400, 310, ObjString.join(''));
}
else {
/**/
}
}
}
}
function AcquireImage() {
if (DWObject) {
var bSelected = DWObject.SelectSource();
if (bSelected) {
var OnAcquireImageSuccess, OnAcquireImageFailure;
OnAcquireImageSuccess = OnAcquireImageFailure = function () {
DWObject.CloseSource();
};
DWObject.OpenSource();
DWObject.IfDisableSourceAfterAcquire = true; //Scanner source will be disabled/closed automatically after the scan.
DWObject.AcquireImage(OnAcquireImageSuccess, OnAcquireImageFailure);
}
}
}
function LoadImages() {
if (DWObject) {
DWObject.Addon.PDF.SetResolution(300);
DWObject.Addon.PDF.SetConvertMode(EnumDWT_ConverMode.CM_RENDERALL);
DWObject.LoadImageEx('', 5,
function () {
},
function (errorCode, errorString) {
alert('Load Image:' + errorString);
}
);
}
}
function OnHttpUploadSuccess() {
console.log('successful');
}
function OnHttpServerReturnedSomething(errorCode, errorString, sHttpResponse) {
//console.log(errorString);
var textFromServer = sHttpResponse;
_printUploadedFiles(textFromServer);
}
function _printUploadedFiles(info) {
//console.log(info);
if (info.indexOf('DWTUploadFileName') != -1) {
var url, _strPort;
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
_strPort = location.port == "" ? 80 : location.port
url = 'http://' + location.hostname + ':' + location.port
if (Dynamsoft.Lib.detect.ssl == true) {
_strPort = location.port == "" ? 443 : location.port;
url = 'https://' + location.hostname + ':' + location.port
}
var savedIntoToDB = false, imgIndexInDB = "-1";
if (info.indexOf("DWTUploadFileIndex:") != -1) {
savedIntoToDB = true;
imgIndexInDB = info.substring(info.indexOf('DWTUploadFileIndex') + 19, info.indexOf('DWTUploadFileName'));
//console.log(imgIndexInDB);
}
var fileName = info.substring(info.indexOf('DWTUploadFileName') + 18, info.indexOf('UploadedFileSize'));
var fileSize = info.substr(info.indexOf('UploadedFileSize') + 17);
if (savedIntoToDB) {
if (info.indexOf('CSHARP') != -1) {
url += CurrentPath + 'action/csharp-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('VBNET') != -1) {
url += CurrentPath + 'action/vbnet-db.aspx?imgID=' + imgIndexInDB;
}
else if (info.indexOf('PHP') != -1) {
url += CurrentPath + 'action/php-mysql.php?imgID=' + imgIndexInDB;
}
else if (info.indexOf('JSP') != -1) {
url += CurrentPath + 'action/jsp-oracle.jsp?imgID=' + imgIndexInDB;
}
}
else {
url += CurrentPath + 'action/UploadedImages/' + encodeURI(fileName);
}
var newTR = document.createElement('tr');
_str = "<td class='tc'><a class='bluelink'" + ' href="' + url + '" target="_blank">' + fileName + "</a></td>"
+ "<td class='tc'>" + fileSize + '</td>';
if (info.indexOf("FieldsTrue:") != -1)
_str += "<td class='tc'><a class='bluelink'" + '" href="' + url.substring(0, url.length - 4) + '_1.txt' + '" target="_blank">Fields</td>';
else {
_str += "<td class='tc'>No Fields</td>";
}
newTR.innerHTML = _str;
document.getElementById('div-uploadedFile').appendChild(newTR);
}
}
function upload_preparation(_name) {
DWObject.IfShowCancelDialogWhenImageTransfer = !document.getElementById('quietScan').checked;
strActionPage = CurrentPath + 'action/';
switch (document.getElementById("ddlLanguages").options.selectedIndex) {
case 0: strActionPage += "php.php"; break;
case 2: strActionPage += "csharp.aspx"; break;
case 6: strActionPage += "jsp.jsp"; break;
case 4: strActionPage += "vbnet.aspx"; break;
case 8: strActionPage += "asp.asp"; break;
case 10: strActionPage += "cfm.cfm"; break;
case 1: strActionPage += "php-mysql.php?imgID=new"; break;
case 7: strActionPage += "jsp-oracle.jsp?imgID=new"; break;
case 3: strActionPage += "csharp-db.aspx?imgID=new"; break;
case 5: strActionPage += "vbnet-db.aspx?imgID=new"; break;
case 9: strActionPage += "asp-db.asp"; break;
case 11: preparetoUploadtoAzure(_name); break;
default: break;
}
DWObject.IfSSL = Dynamsoft.Lib.detect.ssl;
var _strPort = location.port == "" ? 80 : location.port;
if (Dynamsoft.Lib.detect.ssl == true)
_strPort = location.port == "" ? 443 : location.port;
DWObject.HTTPPort = _strPort;
if ([0, 2, 4, 6].indexOf(document.getElementById("ddlLanguages").selectedIndex) != -1) {
/* Add Fields to the Post */
var fields = document.getElementsByClassName('div-fields-item');
DWObject.ClearAllHTTPFormField();
for (var n = 0; n < fields.length; n++) {
var o = fields[n];
if (o.children[0].value != '')
DWObject.SetHTTPFormField(o.children[0].value, o.children[1].value);
}
}
}
function UploadImage_inner() {
if (DWObject.HowManyImagesInBuffer == 0)
return;
var Digital = new Date();
var uploadfilename = Digital.getMilliseconds(); // Uses milliseconds according to local time as the file name
upload_preparation(uploadfilename);
// Upload the image(s) to the server asynchronously
if (document.getElementById("ddlLanguages").options.selectedIndex == 11 /*Azure*/) return;
if (document.getElementsByName('ImageType')[0].checked) {
var uploadIndexes = [];
for (var i = DWObject.HowManyImagesInBuffer - 1; i > -1 ; i--) {
uploadIndexes.push(i);
}
var uploadJPGsOneByOne = function (errorCode, errorString, sHttpResponse) {
if (upload_returnSth)
_printUploadedFiles(sHttpResponse);
if (uploadIndexes.length > 0) {
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
}
var _index = uploadIndexes.pop();
if (upload_returnSth)
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", OnHttpUploadSuccess, uploadJPGsOneByOne);
else
DWObject.HTTPUploadThroughPost(strHTTPServer, _index, strActionPage, uploadfilename + "-" + _index.toString() + ".jpg", uploadJPGsOneByOne, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[1].checked) {
DWObject.HTTPUploadAllThroughPostAsMultiPageTIFF(strHTTPServer, strActionPage, uploadfilename + ".tif", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
else if (document.getElementsByName('ImageType')[2].checked) {
DWObject.HTTPUploadAllThroughPostAsPDF(strHTTPServer, strActionPage, uploadfilename + ".pdf", OnHttpUploadSuccess, OnHttpServerReturnedSomething);
}
}
function UploadImage() {
if (DWObject) {
var nCount = 0, nCountUpLoaded = 0, aryFilePaths = [];
if (document.getElementById('uploadDirectly').checked) {
DWObject.IfShowCancelDialogWhenImageTransfer = false;
function ds_load_file_to_upload_directly(bSave, filesCount, index, path, filename) {
nCount = filesCount;
var filePath = path + "\\" + filename;
aryFilePaths.push(filePath);
if (aryFilePaths.length == nCount) {
upload_preparation();
var i = 0;
function uploadFileOneByOne() {
DWObject.HTTPUploadThroughPostDirectly(strHTTPServer, filePath, strActionPage, filename,
function () {
console.log('Upload Image:' + aryFilePaths[i] + ' -- successful');
i++;
if (i != nCount)
uploadFileOneByOne();
else
DWObject.UnregisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
},
OnHttpServerReturnedSomething
);
}
uploadFileOneByOne();
}
}
DWObject.RegisterEvent('OnGetFilePath', ds_load_file_to_upload_directly);
DWObject.ShowFileDialog(false, "Any File | *.*", 0, "", "", true, true, 0);
}
else {
UploadImage_inner();
}
}
}
/*******************/
/* Upload to Azure */
var Base64Binary = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
decode: function (input, arrayBuffer) {
//get last chars to see if are valid
var lkey1 = this._keyStr.indexOf(input.charAt(input.length - 1));
var lkey2 = this._keyStr.indexOf(input.charAt(input.length - 2));
var bytes = (input.length / 4) * 3;
if (lkey1 == 64) bytes--; //padding chars, so skip
if (lkey2 == 64) bytes--; //padding chars, so skip
var uarray;
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var j = 0;
if (arrayBuffer)
uarray = new Uint8Array(arrayBuffer);
else
uarray = new Uint8Array(bytes);
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
for (i = 0; i < bytes; i += 3) {
//get the 3 octects in 4 ascii chars
enc1 = this._keyStr.indexOf(input.charAt(j++));
enc2 = this._keyStr.indexOf(input.charAt(j++));
enc3 = this._keyStr.indexOf(input.charAt(j++));
enc4 = this._keyStr.indexOf(input.charAt(j++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
uarray[i] = chr1;
if (enc3 != 64) uarray[i + 1] = chr2;
if (enc4 != 64) uarray[i + 2] = chr3;
}
return uarray;
}
}
function uploadImageInner_azure(blobSasUrl, fileDataAsArrayBuffer) {
var ajaxRequest = new XMLHttpRequest();
try {
ajaxRequest.open('PUT', blobSasUrl, true);
ajaxRequest.setRequestHeader('x-ms-blob-type', 'BlockBlob');
ajaxRequest.send(fileDataAsArrayBuffer);
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
console.log('Upload image to azure server successfully.');
}
}
}
catch (e) {
console.log("can't upload the image to server.\n" + e.toString());
}
}
function preparetoUploadtoAzure(__name) {
var uploadfilename = '';
//For JPEG, upload the current image
if (document.getElementsByName('ImageType')[0].checked) {
DWObject.SelectedImagesCount = 1;
DWObject.SetSelectedImageIndex(0, DWObject.CurrentImageIndexInBuffer);
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_JPG);
uploadfilename = __name + '.jpg';
}
else { //For TIFF, PDF, upload all images
var count = DWObject.HowManyImagesInBuffer;
DWObject.SelectedImagesCount = count;
for (var i = 0; i < count; i++) {
DWObject.SetSelectedImageIndex(i, i);
}
if (document.getElementsByName('ImageType')[1].checked) {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_TIF);
uploadfilename = __name + '.tif';
}
else {
DWObject.GetSelectedImagesSize(EnumDWT_ImageType.IT_PDF);
uploadfilename = __name + '.pdf';
}
}
var strImg, aryImg, _uint8_STR, _bin_ARR, _blobImg;
strImg = DWObject.SaveSelectedImagesToBase64Binary();
// convert base64 to Uint8Array
var bytes = (strImg.length / 4) * 3;
var _temp = new ArrayBuffer(bytes);
_uint8_STR = Base64Binary.decode(strImg, _temp);
// convert Uint8Array to blob
_blobImg = new Blob([_uint8_STR]);
// upload to Azure server
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
uploadImageInner_azure(xhr.responseText, _blobImg);
}
}
var actionPageFullPath = CurrentPath + 'action/' + 'azure.aspx?imageName=' + uploadfilename;
xhr.open('GET', actionPageFullPath, true);
xhr.send();
}
/*******************/
The German Tax Id (Steueridentifikationsnummer) has the following properties:
It has 11 digits
First digit cannot be 0
In the first ten digits: one number occurs exactly twice or thrice, one or two digits appear zero times and the other digits appear exactly once
The last digit is a checksum Example Code for Checksum
The third bulletpoint is a little difficult for me to solve in an elegant way. I already have the code for the other three bulletpoints, but would love to get input for the last one, so that this could be a small little reference for other people.
# validate tax number
$taxNumber = $_POST['taxNumber'];
echo preg_replace("/[^0-9]/", "", $taxNumber);
if (strlen($taxNumber != 11)) {
# 11 digits
$taxNumberValid = false;
} else if ($taxNumber[0] == "0") {
# first digit != 0
$taxNumberValid = false;
} else {
# one digit two times, one digit zero times
# checksum
$numbers = str_split($taxNumber);
$sum = 0;
$product = 10;
for ($i = 0; $i <= 9; $i++) {
$sum = ($numbers[$i] + $product) % 10;
if ($sum == 0) {
$sum = 10;
}
$product = ($sum * 2) % 11;
}
$checksum = 11 - $product;
if ($checksum == 10) {
$checksum = 0;
}
if ($taxNumber[10] != $checksum) {
$taxNumberValid = false;
}
}
This code solves the problem:
// remove whitespaces, slashes & other unnecessary characters
$taxNumber = preg_replace("/[^0-9]/", "", $taxNumber);
// by default the taxnumber is correct
$taxNumberValid = true;
// taxnumber has to have exactly 11 digits
if (strlen($taxNumber) != 11) {
$taxNumberValid = false;
}
// first digit cannot be 0
if ($taxNumber[0] == "0") {
$taxNumberValid = false;
}
/*
make sure that within the first ten digits:
1.) one digit appears exactly twice or thrice
2.) one or two digits appear zero times
3.) and oll other digits appear exactly once once
*/
$digits = str_split($taxNumber);
$first10Digits = $digits;
array_pop($first10Digits);
$countDigits = array_count_values ($first10Digits);
if (count($countDigits) != 9 && count($countDigits) != 8) {
$taxNumberValid = false;
}
// last check: 11th digit has to be the correct checkums
// see http://de.wikipedia.org/wiki/Steueridentifikationsnummer#Aufbau_der_Identifikationsnummer
$sum = 0;
$product = 10;
for($i = 0; $i <= 9; $i++) {
$sum = ($digits[$i] + $product) % 10;
if ($sum == 0) {
$sum = 10;
}
$product = ($sum * 2) % 11;
}
$checksum = 11 - $product;
if ($checksum == 10) {
$checksum = 0;
}
if ($taxNumber[10] != $checksum) {
$taxNumberValid = false;
}
Update in 2017
Until 2016, the rule was, that within the first ten digits one number had to appear exactly twice.
Starting at 2017, the rule is, that within the first ten digits one number has to appear exactly twice or thrice.
And here is how you would write it in JS, based on #Pascal Klein's answer:
function countValues(arr) {
return arr.reduce((obj, item) => {
obj[item] = obj[item] ? ++obj[item] : 1;
return obj;
}, {});
}
function validateTIN(tin) {
const tinLength = 11;
// Taxnumber has to have exactly 11 digits.
if (tin.length !== tinLength) {
return false;
}
// First digit cannot be 0.
if (tin[0] === '0') {
return false;
}
/*
make sure that within the first ten digits:
1.) one digit appears exactly twice or thrice
2.) one or two digits appear zero times
3.) and all other digits appear exactly once
*/
const tinArray = tin.split('').slice(0, -1);
const valueCount = countValues(tinArray);
const valueCountLength = Object.keys(valueCount).length;
if (valueCountLength !== 8 && valueCountLength !== 9) {
return false;
}
// 11th digit has to match the checkum.
let sum = 0;
let product = 10;
for(let i = 0; i < tinLength - 1; i++) {
sum = (+tinArray[i] + product) % 10;
if (sum === 0) {
sum = 10;
}
product = (sum * 2) % 11;
}
let checksum = 11 - product;
if (checksum === 10) {
checksum = 0;
}
if (+tin[tinLength - 1] !== checksum) {
return false;
}
return true;
}
const tin1 = 'gbg';
const tin2 = '42344677908';
const tin3 = '12005078909';
const tin4 = '36574261809'; // valid
const tin5 = '10863924976'; // valid
console.log(tin1, validateTIN(tin1));
console.log(tin2, validateTIN(tin2));
console.log(tin3, validateTIN(tin3));
console.log(tin4, validateTIN(tin4));
console.log(tin5, validateTIN(tin5));
Here's a solution (in Javascript) that takes all the rules in consideration.
function validateTin(tin) {
// Allow space and slash (/) as number separators
tin = tin.replace(/ |\//g, "");
// 11 digits, the first is not allowed to be 0
if (!/^[1-9][0-9]{10}$/.test(tin)) {
return false;
}
const firstTen = tin.slice(0, 10);
// Count the number of occurrences of each digit
const occurrences = firstTen
.split("")
.reduce((acc, d) => acc.set(d, (acc.get(d) || 0) + 1), new Map());
const keys = [...occurrences.keys()];
const values = [...occurrences.values()];
// If one digit occurs twice, the length of keys will be 9
// If one digit occurs three times OR if two different digits occurs twice
// each, the length will be 8
if (keys.length !== 9 && keys.length !== 8) {
return false;
}
if (keys.length === 8) {
// Check how many times the digit that occurred the most times occurred
const maxOccurrences = values.reduce((max, num) => Math.max(max, num));
// If maxOccurrences is 2, we know two different numbers occurred twice
// each. This is not a valid tin.
// A final restriction is that a number can not occur three times in a row
if (maxOccurrences === 2 || /(\d)\1\1/.test(firstTen)) {
return false;
}
}
// Calculate the checksum digit
let m11 = 10;
let m10 = 0;
for (let i = 0; i < 10; i++) {
m10 = (parseInt(tin[i], 10) + m11) % 10;
if (m10 === 0) {
m10 = 10;
}
m11 = (2 * m10) % 11;
}
let digit = 11 - m11;
if (digit === 10) {
digit = 0;
}
return digit === parseInt(tin[10], 10);
}
I am wondering if there is a rot5 function for PHP equalivant too
function rot5(str) {
var s = [];
for (i = 0; i < str.length; i ++)
{
idx = str.charCodeAt(i);
if ((idx >= 48) && (idx <= 57))
{
if (idx <= 52)
{
s[i] = String.fromCharCode(((idx + 5)));
}
else
{
s[i] = String.fromCharCode(((idx - 5)));
}
}
else
{
s[i] = String.fromCharCode(idx);
}
}
return s.join('');
}
In javascript? If not then how can I do fromCharCode and charCodeAt in PHP?
Here you got generic strrot with default to strrot5
<?php
function strrot($str, $n=5){
$replace = [];
for($i=0;$i<26;$i++){
$replace[chr(65+$i)] = chr(65+(($i+$n)%26));
$replace[chr(97+$i)] = chr(97+(($i+$n)%26));
}
return strtr($str, $replace);
}
You can use 'ord' for 'charCodeAt'.
ord($yourstring[$yourindex])
You can use 'chr' for 'fromCharCode'
chr($yourcharcode)
PHP Function:
function formatNumberForDisplay($number, $decimal=0, $decimalSeperator='.', $numberSeperator=',')
{
return number_format($number, $decimal, $decimalSeperator, $numberSeperator);
}
Can anybody suggest to me the equivalent functionality in jQuery/JavaScript?
The same equivalent of number_format in js can found here
function number_format (number, decimals, dec_point, thousands_sep) {
// Strip all characters but numerical ones.
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');
}
return s.join(dec);
}
Just use toLocaleString on an integer object.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility
let x = 1234567;
//if x is a string/non-number, use parseInt/parseFloat to convert to a number. Thanks #Aleksandr Kopelevich
x.toLocaleString('us', {minimumFractionDigits: 2, maximumFractionDigits: 2})
is this what you'd like to get?
yourFloatVarHere.toFixed(2);
voilà.
Native "Intl" object approach:
var amount = 5000.25;
var locale = 'de';
var options = {style: 'currency', currency: 'eur', minimumFractionDigits: 2, maximumFractionDigits: 2};
var formatter = new Intl.NumberFormat(locale, options);
console.log(formatter.format(amount));
http://jsfiddle.net/arturrelax/sa9jL138/1/
More information at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
I know it's an old thread, but I made my own function, which is in pure Javascript.
Simple Solution
https://gist.github.com/VassilisPallas/d73632e9de4794b7dd10b7408f7948e8/bf17eccef8521b4e5869bdc6a5b09a771356fbff
This works fine with finite numbers
function number_format(number, decimals, dec_point, thousands_point) {
if (number == null || !isFinite(number)) {
throw new TypeError("number is not valid");
}
if (!decimals) {
var len = number.toString().split('.').length;
decimals = len > 1 ? len : 0;
}
if (!dec_point) {
dec_point = '.';
}
if (!thousands_point) {
thousands_point = ',';
}
number = parseFloat(number).toFixed(decimals);
number = number.replace(".", dec_point);
var splitNum = number.split(dec_point);
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
number = splitNum.join(dec_point);
return number;
}
Complex Solution
This solves the issue with big numbers
https://gist.github.com/VassilisPallas/d73632e9de4794b7dd10b7408f7948e8
const splitThousands = (number) => (dec_point, thousands_point) => {
const splitNum = number.toString().split(dec_point);
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
return splitNum.join(dec_point);
};
const isBigNumber = (number) => number.toString().includes("e");
const isBigFloat = (number) => number.toString().includes("-");
const calcTrailing = (dec, len) => Number(dec) + 2 - len;
const handleBigFloats = (number, decimals) => {
if (!decimals) {
return "0";
}
const [numbers, dec] = number.toString().replace(".", "").split("e-");
const trailingZeros = calcTrailing(dec, numbers.length);
const res = `${"0.".padEnd(trailingZeros + 2, "0")}${numbers}`;
return decimals ? res.substring(0, 2) + res.substring(2, decimals + 2) : res;
};
const handleBigNumbers = (number, decimals, dec_point, thousands_point) => {
if (isBigFloat(number)) {
return handleBigFloats(number, decimals);
}
return splitThousands(BigInt(number))(dec_point, thousands_point);
};
function handleFiniteNumbers(number, decimals, dec_point, thousands_point) {
if (!isFinite(number)) {
throw new TypeError("number is not finite number");
}
if (!decimals) {
const len = number.toString().split(".").length;
decimals = len > 1 ? len : 0;
}
return splitThousands(
parseFloat(number).toFixed(decimals).replace(".", dec_point)
)(dec_point, thousands_point);
}
const numberFormat = (
number,
decimals,
dec_point = ".",
thousands_point = ","
) => {
if (number == null || typeof number !== "number") {
throw new TypeError("number is not valid");
}
if (isBigNumber(number)) {
return handleBigNumbers(number, decimals, dec_point, thousands_point);
}
return handleFiniteNumbers(number, decimals, dec_point, thousands_point);
};
https://jsfiddle.net/p2ft9n4v/1/
Closer function to php number_format($number) should be number.toLocaleString('en') of javascript
Here is another short solution that should behaviour like the php-equivalent.
function number_format(number,decimals,dec_point,thousands_sep) {
number = number*1;//makes sure `number` is numeric value
var str = number.toFixed(decimals?decimals:0).toString().split('.');
var parts = [];
for ( var i=str[0].length; i>0; i-=3 ) {
parts.unshift(str[0].substring(Math.max(0,i-3),i));
}
str[0] = parts.join(thousands_sep?thousands_sep:',');
return str.join(dec_point?dec_point:'.');
}
Here is a simple function that you can use to achieve almost the same result of number_format in php:
function number_format(user_input){
var filtered_number = user_input.replace(/[^0-9]/gi, '');
var length = filtered_number.length;
var breakpoint = 1;
var formated_number = '';
for(i = 1; i <= length; i++){
if(breakpoint > 3){
breakpoint = 1;
formated_number = ',' + formated_number;
}
var next_letter = i + 1;
formated_number = filtered_number.substring(length - i, length - (i - 1)) + formated_number;
breakpoint++;
}
return formated_number;
}
Another way is to use ajax to make a call to a php script where you run number_format on the number and return it with ajax as a string. But it`s a bit messy.
It no easy, try to use simple jquery-plugins such as:
jquery-numberformatter
Jquery-Price-Format
My take on this:
var number_format = function(num) {
stringNum = num.toString();
stringNum = stringNum.split("");
c = 0;
if (stringNum.length>3) {
for (i=stringNum.length; i>-1; i--) {
if ( (c==3) && ((stringNum.length-i)!=stringNum.length) ) {
stringNum.splice(i, 0, ",");
c=0;
}
c++
}
return stringNum;
}
return num;
}
$("body").append(number_format(100000000));
Another variant of exposed examples:
const numberFormat = (value, decimals, decPoint, thousandsSep) => {
decPoint = decPoint || '.';
decimals = decimals !== undefined ? decimals : 2;
thousandsSep = thousandsSep || ' ';
if (typeof value === 'string') {
value = parseFloat(value);
}
let result = value.toLocaleString('en-US', {
maximumFractionDigits: decimals,
minimumFractionDigits: decimals
});
let pieces = result.split('.');
pieces[0] = pieces[0].split(',').join(thousandsSep);
return pieces.join(decPoint);
};
The JS equivalent will be:
var number = //input value
parseFloat(number).toFixed(3);
I'm to do it just calling the JS function as follows and it works:
var formattedNumber = number_format(value)
Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString("format_provider") or String.Format()?
Generally
Formatting numbers in JavaScript
Formatting numbers for currency display and more.
In jQuery
autoNumeric (a decent number formatter & input helper with locale support for jQuery 1.5+)
jQuery Format (a clientSide implementation of Java's SimpleDateFormat and NumberFormat)
jquery-numberformatter (number formatter with locale support)
Yes, there is definitely a way to format numbers properly in javascript, for example:
var val=2489.8237
val.toFixed(3) //returns 2489.824 (round up)
val.toFixed(2) //returns 2489.82
val.toFixed(7) //returns 2489.8237000 (padding)
With the use of variablename.toFixed .
And there is another function toPrecision() .
For more detail you also can visit
http://raovishal.blogspot.com/2012/01/number-format-in-javascript.html
Here's a simple JS function to add commas to an integer number in string format. It will handle whole numbers or decimal numbers. You can pass it either a number or a string. It obviously returns a string.
function addCommas(str) {
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
first = main.charAt(0),
i;
if (first === '-') {
main = main.slice(1);
len = main.length;
} else {
first = "";
}
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = "," + output;
}
--i;
}
// put sign back
output = first + output;
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
Here's a set of test cases: http://jsfiddle.net/jfriend00/6y57j/
You can see it being used in this previous jsFiddle: http://jsfiddle.net/jfriend00/sMnjT/. You can find functions that will handle decimal numbers too with a simple Google search for "javascript add commas".
Converting a number to a string can be done many ways. The easiest is just to add it to a string:
var myNumber = 3;
var myStr = "" + myNumber; // "3"
Within, the context of your jsFiddle, you'd get commas into the counter by changing this line:
jTarget.text(current);
to this:
jTarget.text(addCommas(current));
You can see it working here: http://jsfiddle.net/jfriend00/CbjSX/
I wrote a simple function (not yet another jQuery plugin needed!!) that converts a number to a decimal separated string or an empty string if the number wasn't a number to begin with:
function format(x) {
return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
format(578999); results in 578,999
format(10); results in 10
if you want to have a decimal point instead of a comma simply replace the comma in the code with a decimal point.
One of the comments correctly stated this only works for integers, with a few small adaptions you can make it work for floating points as well:
function format(x) {
if(isNaN(x))return "";
n= x.toString().split('.');
return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")+(n.length>1?"."+n[1]:"");
}
Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.
Method 0 (RegExp)
Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.
if (typeof Number.prototype.format === 'undefined') {
Number.prototype.format = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
return a.join('.');
}
}
Method 1
if (typeof Number.prototype.format1 === 'undefined') {
Number.prototype.format1 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.'),
// skip the '-' sign
head = Number(this < 0);
// skip the digits that's before the first thousands separator
head += (a[0].length - head) % 3 || 3;
a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
return a.join('.');
};
}
Method 2 (Split to Array)
if (typeof Number.prototype.format2 === 'undefined') {
Number.prototype.format2 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0]
.split('').reverse().join('')
.replace(/\d{3}(?=\d)/g, '$&,')
.split('').reverse().join('');
return a.join('.');
};
}
Method 3 (Loop)
if (typeof Number.prototype.format3 === 'undefined') {
Number.prototype.format3 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('');
a.push('.');
var i = a.indexOf('.') - 3;
while (i > 0 && a[i-1] !== '-') {
a.splice(i, 0, ',');
i -= 3;
}
a.pop();
return a.join('');
};
}
Example
console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
n = (n * 10) + (i % 10)/100;
console.log(n.format(2), (-n).format(2));
}
Separator
If we want custom thousands separator or decimal separator, use replace():
123456.78.format(2).replace(',', ' ').replace('.', ' ');
Test suite
function assertEqual(a, b) {
if (a !== b) {
throw a + ' !== ' + b;
}
}
function test(format_function) {
console.log(format_function);
assertEqual('NaN', format_function.call(NaN, 0))
assertEqual('Infinity', format_function.call(Infinity, 0))
assertEqual('-Infinity', format_function.call(-Infinity, 0))
assertEqual('0', format_function.call(0, 0))
assertEqual('0.00', format_function.call(0, 2))
assertEqual('1', format_function.call(1, 0))
assertEqual('-1', format_function.call(-1, 0))
// decimal padding
assertEqual('1.00', format_function.call(1, 2))
assertEqual('-1.00', format_function.call(-1, 2))
// decimal rounding
assertEqual('0.12', format_function.call(0.123456, 2))
assertEqual('0.1235', format_function.call(0.123456, 4))
assertEqual('-0.12', format_function.call(-0.123456, 2))
assertEqual('-0.1235', format_function.call(-0.123456, 4))
// thousands separator
assertEqual('1,234', format_function.call(1234.123456, 0))
assertEqual('12,345', format_function.call(12345.123456, 0))
assertEqual('123,456', format_function.call(123456.123456, 0))
assertEqual('1,234,567', format_function.call(1234567.123456, 0))
assertEqual('12,345,678', format_function.call(12345678.123456, 0))
assertEqual('123,456,789', format_function.call(123456789.123456, 0))
assertEqual('-1,234', format_function.call(-1234.123456, 0))
assertEqual('-12,345', format_function.call(-12345.123456, 0))
assertEqual('-123,456', format_function.call(-123456.123456, 0))
assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
// thousands separator and decimal
assertEqual('1,234.12', format_function.call(1234.123456, 2))
assertEqual('12,345.12', format_function.call(12345.123456, 2))
assertEqual('123,456.12', format_function.call(123456.123456, 2))
assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}
console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);
Benchmark
function benchmark(f) {
var start = new Date().getTime();
f();
return new Date().getTime() - start;
}
function benchmark_format(f) {
console.log(f);
time = benchmark(function () {
for (var i = 0; i < 100000; i++) {
f.call(123456789, 0);
f.call(123456789, 2);
}
});
console.log(time.format(0) + 'ms');
}
async = [];
function next() {
setTimeout(function () {
f = async.shift();
f && f();
next();
}, 10);
}
console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();
If you don't want to use jQuery, take a look at Numeral.js
Firstly, converting an integer into string in JS is really simple:
// Start off with a number
var number = 42;
// Convert into a string by appending an empty (or whatever you like as a string) to it
var string = 42+'';
// No extra conversion is needed, even though you could actually do
var alsoString = number.toString();
If you have a number as a string and want it to be turned to an integer, you have to use the parseInt(string) for integers and parseFloat(string) for floats. Both of these functions then return the desired integer/float. Example:
// Start off with a float as a string
var stringFloat = '3.14';
// And an int as a string
var stringInt = '42';
// typeof stringInt would give you 'string'
// Get the real float from the string
var realFloat = parseFloat(someFloat);
// Same for the int
var realInt = parseInt(stringInt);
// but typeof realInt will now give you 'number'
What exactly are you trying to append etc, remains unclear to me from your question.
http://code.google.com/p/javascript-number-formatter/ :
Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
Accept standard number formatting like #,##0.00 or with negation -000.####.
Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
Auto number rounding.
Simple interface, just supply mask & value like this: format( "0.0000", 3.141592)
UPDATE
As say Tomáš Zato here one line solution:
(666.0).toLocaleString()
numObj.toLocaleString([locales [, options]])
which described in ECMA-262 5.1 Edition:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
and will work in future versions of browsers...
For example:
var flt = '5.99';
var nt = '6';
var rflt = parseFloat(flt);
var rnt = parseInt(nt);
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
To get a decimal with 2 numbers after the comma, you could just use:
function nformat(a) {
var b = parseInt(parseFloat(a)*100)/100;
return b.toFixed(2);
}
May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.
Here's another version:
$.fn.digits = function () {
return this.each(function () {
var value = $(this).text();
var decimal = "";
if (value) {
var pos = value.indexOf(".");
if (pos >= 0) {
decimal = value.substring(pos);
value = value.substring(0, pos);
}
if (value) {
value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
$(this).text(value);
}
}
else {
value = $(this).val()
if (value) {
var pos = value.indexOf(".");
if (pos >= 0) {
decimal = value.substring(pos);
value = value.substring(0, pos);
}
if (value) {
value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
$(this).val(value);
}
}
}
})
};
I made a simple function, maybe someone can use it
function secsToTime(secs){
function format(number){
if(number===0){
return '00';
}else {
if (number < 10) {
return '0' + number
} else{
return ''+number;
}
}
}
var minutes = Math.floor(secs/60)%60;
var hours = Math.floor(secs/(60*60))%24;
var days = Math.floor(secs/(60*60*24));
var seconds = Math.floor(secs)%60;
return (days>0? days+"d " : "")+format(hours)+':'+format(minutes)+':'+format(seconds);
}
this can generate the followings outputs:
5d 02:53:39
4d 22:15:16
03:01:05
00:00:00
In case you want to format number for view rather than for calculation you can use this
function numberFormat( number ){
var digitCount = (number+"").length;
var formatedNumber = number+"";
var ind = digitCount%3 || 3;
var temparr = formatedNumber.split('');
if( digitCount > 3 && digitCount <= 6 ){
temparr.splice(ind,0,',');
formatedNumber = temparr.join('');
}else if (digitCount >= 7 && digitCount <= 15) {
var temparr2 = temparr.slice(0, ind);
temparr2.push(',');
temparr2.push(temparr[ind]);
temparr2.push(temparr[ind + 1]);
// temparr2.push( temparr[ind + 2] );
if (digitCount >= 7 && digitCount <= 9) {
temparr2.push(" million");
} else if (digitCount >= 10 && digitCount <= 12) {
temparr2.push(" billion");
} else if (digitCount >= 13 && digitCount <= 15) {
temparr2.push(" trillion");
}
formatedNumber = temparr2.join('');
}
return formatedNumber;
}
Input: {Integer} Number
Outputs: {String} Number
22,870 => if number 22870
22,87 million => if number 2287xxxx (x can be whatever)
22,87 billion => if number 2287xxxxxxx
22,87 trillion => if number 2287xxxxxxxxxx
You get the idea
To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:
function log(args) {
var str = "";
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === "object") {
str += JSON.stringify(arguments[i]);
} else {
str += arguments[i];
}
}
var div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
}
Number.prototype.addCommas = function (str) {
if (str === undefined) {
str = this;
}
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
first = main.charAt(0),
i;
if (first === '-') {
main = main.slice(1);
len = main.length;
} else {
first = "";
}
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = "," + output;
}
--i;
}
// put sign back
output = first + output;
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
var testCases = [
1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,
-1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1
];
for (var i = 0; i < testCases.length; i++) {
log(testCases[i].addCommas());
}
/*for (var i = 0; i < testCases.length; i++) {
log(Number.addCommas(testCases[i]));
}*/
You can do it in the following way:
So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.
function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
const roundedNumber = number.toFixed(decimals);
let integerPart = '', fractionalPart = '';
if (decimals == 0) {
integerPart = roundedNumber;
decimalSeparator = '';
} else {
let numberParts = roundedNumber.split('.');
integerPart = numberParts[0];
fractionalPart = numberParts[1];
}
integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
return `${integerPart}${decimalSeparator}${fractionalPart}`;
}
Use:
let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
let randomNumber = Math.random() * (max - min) + min;
let formated = format(randomNumber, 4, ',', '.'); // formated number
console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');