Working with money in JavaScript

Here are some great techinques that I have come up with while working as paperless applications developer at SVC:

Working with money can require a lot of scripts to ensure sucessful data entry , transfer and saving.

One thing that comes up is the errors that users can make when entering the figures for money into a form. The forms will have many different requirements for entering the monetary information, such as type of figures desired. For example, on one form, I need the user to only enter a whole dollar amount, and I need to make sure that no dollar signs, cent signs or punctuation make it into the calculations for totals.

Here is a script to clean an entry of all dollar signs, cent signs,  punctuation  and ensure that whole dollar amounts are entered. For this usage, I have set up the function to be passed a Jquery object of a textfield , and the function will get the value, fix it and put it back in.
[code language=”javascript”]
// strip out any $$ .00 and anything else
function stripper(who){
dirtynumber = $( who ).val();
cleannumber = parseInt(dirtynumber.replace(/[^d.]/g, “”));
if(isNaN(cleannumber)){cleannumber=0;}
$( who ).val(cleannumber); }
[/code]

Here is a script to compare two values to make sure they are the same:

[code language=”html”]
// ensure budget items total match budget request
var amount1 =  parseInt($(“#fund_request”).val().replace(/[^d.]/g, “”));
var amount2 =  parseInt($(“#justification_budget_total”).val().replace(/[^d.]/g, “”));
if(isNaN(amount1)){amount1=0}
if(isNaN(amount2)){amount2=0}
if(amount1 !== amount2){alert(“The total budget request : ” + amount1 + ” doesn’t equal the budget justification item total: ” + amount2 + “. Please check your numbers and re submit.”);return false;}
[/code]

Leave a Reply