I was having problems with displaying money format (Rp. 1.000.000,- and not 1000000) in a form field and came up with this solution:
Made using jquery
Ideally, it would be better if the input field displays the formatted number directly and if clicked, then it shows the unformatted number for editing like what we usually see in most spreadsheet. Anybody knows how to do something like that?
Updated
Nevermind, I did it with this simple jquery codes:
this.numberformat = function(){ $("input.numberformat").focus(function(e) { this.value = stripToMoney(this.value); }).blur(function(e) { this.value = DecimalAsString(this.value); }); }; |
This is as simple as formatting the numbers on blur (out from focus) so that it would look formatted when your cursor are not in that field, and strip the input field from dots (.), comma (,) and strip (-) when the cursor are in the field. Here’s the code for striping the format:
function stripToMoney(words,character) { var spaces = words.length; for(var x = 1; x<spaces ; ++x){ words = words.replace("-", ""); words = words.replace(".", ""); words = words.replace(",", ""); } return words; } |
And here’s the one to format the number into groups of 3 and separate it with a dot (.), something like (1.000.000):
function DecimalAsString(value) { var i = parseFloat(value); if(isNaN(i)) { i = 0; } var minus = ''; if(i < 0) { minus = '-'; } i = Math.abs(i); i = parseInt((i + .005) * 100); i = i / 100; s = new String(i); if(s.indexOf('.') < 0) { s += ',-'; } s = minus + s; return FormatNumberBy3(s); } function FormatNumberBy3(num, decpoint, sep) { // check for missing parameters and use defaults if so if (arguments.length == 2) { sep = "."; } if (arguments.length == 1) { sep = "."; decpoint = ","; } // need a string for operations num = num.toString(); // separate the whole number and the fraction if possible a = num.split(decpoint); x = a[0]; // decimal y = a[1]; // fraction z = ""; if (typeof(x) != "undefined") { // reverse the digits. regexp works from left to right. for (i=x.length-1;i>=0;i--) z += x.charAt(i); // add seperators. but undo the trailing one, if there z = z.replace(/(\d{3})/g, "$1" + sep); if (z.slice(-sep.length) == sep) z = z.slice(0, -sep.length); x = ""; // reverse again to get back the number for (i=z.length-1;i>=0;i--) x += z.charAt(i); // add the fraction back in, if it was there if (typeof(y) != "undefined" && y.length > 0) x += decpoint + y; } return x; } |
And of course, don’t forget to run the function on document.ready
$(document).ready(function(){ numberformat(); $("input.numberformat").each(function(e){ $(this).setValue(DecimalAsString($(this).getValue())); // Apply the decimal as string to all }); }); |
Enjoy!








September 21st, 2008 at 12:55 am
geeks