Skip to content

Instantly share code, notes, and snippets.

@adityadees
Last active June 4, 2021 03:06
Show Gist options
  • Save adityadees/5982a9c610dc1830a43acb5815e7270a to your computer and use it in GitHub Desktop.
Save adityadees/5982a9c610dc1830a43acb5815e7270a to your computer and use it in GitHub Desktop.
JS Input format currecy
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
$("input[data-type='currency']").on({
keyup: function() {
formatCurrency($(this));
},
blur: function() {
formatCurrency($(this), "blur");
}
});
function formatNumber(n) {
return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
function formatCurrency(input, blur) {
var input_val = input.val();
if (input_val === "") { return; }
var original_len = input_val.length;
var caret_pos = input.prop("selectionStart");
if (input_val.indexOf(".") >= 0) {
var decimal_pos = input_val.indexOf(".");
var left_side = input_val.substring(0, decimal_pos);
var right_side = input_val.substring(decimal_pos);
left_side = formatNumber(left_side);
right_side = formatNumber(right_side);
if (blur === "blur") {
right_side += "00";
}
right_side = right_side.substring(0, 2);
input_val = "Rp" + left_side + "." + right_side;
} else {
input_val = formatNumber(input_val);
input_val = "Rp" + input_val;
if (blur === "blur") {
input_val += ".00";
}
}
input.val(input_val);
var updated_len = input_val.length;
caret_pos = updated_len - original_len + caret_pos;
input[0].setSelectionRange(caret_pos, caret_pos);
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment