Javascript tax calculator need help to make sure its currency

Discussion in 'JavaScript' started by Camay123, Jun 10, 2011.

  1. #1
    Hi,

    I made javascript code to calculate land transfer taxes. Basically the rules are:

    • Transaction under 5000$ = no tax
    • Transaction till 50000$ = 0,5% tax
    • Transaction upto 250000$ = 0,5% for first 50000$, rest is 1,0%
    • Transaction upto 500000$ = 0,5% for first 50000$, 1,0% for next 200000$ and 1,5% for everything over 250000$

    I made this script:

    function calculerTaxeDeBienvenue(){
    	
    	var montant = document.getElementById("valeur").value;
    	montant = montant.replace(' ', '', 'g');
    	montant = montant.replace(',', '', 'g');
    	var resultat = 0;
    	
    	pageTracker._trackPageview('/taxedebienvenue/'+montant);
    	
    	montant = parseInt(montant);
    	
    	if (montant<5000){
    	tropbas = "Il n'y aura pas de droits de mutation, or la ville pourrait charger un frais d'administration de 200,00$ maximum."
    	document.getElementById("resultat").innerHTML = tropbas;
    	}
    	
    	else {
    	
    	tranche3 = montant - 250000;
    	if(tranche3>0) {
    		resultat += (tranche3*1.5/100);
    		montant -= tranche3;
    	}
    	
    	tranche2 = montant - 50000;
    	if(tranche2>0) {
    		resultat += (tranche2*1.0/100);
    		montant -= tranche2;
    	}
    	
    	tranche1 = montant;
    	if(tranche1>0) {
    		resultat += (tranche1*0.5/100);
    		montant -= tranche1;
    	}
    	
    	document.getElementById("resultat").innerHTML = resultat+ "$, sera le montant de droit de mutation.";
    	}
    }
    Code (markup):
    However,

    I dont know how ensure that people are entering amounts in dollars with either a comma or a dot as a separator for decimal, and that the tax will be calculated accordingly. Any help ?
     
    Camay123, Jun 10, 2011 IP
  2. rainborick

    rainborick Well-Known Member

    Messages:
    424
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    120
    #2
    Your code might be better if you use:
    
    montant = montant.replace(/\s/g, '');
    montant = montant.replace(/\$/g, '');
    montant = montant.replace(/,/g, '.');
    
    Code (markup):
    so that the code is cross-browser compatible, all spaces and $'s are removed, and the commas are replaced with decimal points/periods so that you can re-use the code elsewhere. From there, you can test to make sure that the variable contains only numbers and decimal point/periods.
     
    rainborick, Jun 10, 2011 IP