New Posts  All Forums:Forum Nav:

Currency conversion

post #1 of 5
Thread Starter 
My teacher wants me to use a text box to choose the currency instead of my dropbox. How would i check if the user typed in USD or CAD?



HTML
Code:
<html>

<head>
        <script type="text/javascript" src="CurrencyConverter.js"></script>
        <title>A2:</title>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <link href="CurrencyConverter.css" rel="stylesheet" type="text/css">
</head>



<body>
        <div>
         <form>
                <label for="amount">How many dollars?:</label>
                <input type="text" id="amount" value=""><br />
                <select id="select">
                    <option value="USD to CAD">USD to EUR</option>
                    <option value ="CAD to USD">EUR to USD</option>
                </select>
                <input type="text" id="result" value="">
                <input type="button" value="Click here to convert!" onclick="calculate();">
           
        </form>
        </div>
    
    <script>
        $( "div" ).css("border", "9px", "solid", "black" );
        </script>

</body>

</html>

Javascript
Code:
function calculate() {
            var amount = parseFloat(document.getElementById("amount").value);
            var select = document.getElementById("select");
            var result = document.getElementById("result");
                                
            if (select.value === "USD to CAD") {
                result.value = (amount * 1.0138).toFixed(2);
            }
            if (select.value === "CAD to USD") {
                result.value = (amount * 0.9864).toFixed(2);
            }
                         if(isNaN(amount) || amount === 0){
                                 alert("Please enter a correct value!");
                         }else {
                                 return ;
                         }
        }
post #2 of 5
It's going to be almost the same. You can read the value property of the text input the same as the dropdown and then just change the conditions you have their to specifically look for "USD" or "CAD".

As a side note, I'd move the validation of the amount before doing any calculations. Otherwise you'll get "NaN" in your result text input when someone enters something stupid.
    
CPUMotherboardGraphicsRAM
i7 920 D0 MSI X58 Pro-E GTX 560 Ti 448 3x2GB G.Skill DDR3-1333 9-9-9-24 
Hard DriveHard DriveOptical DriveOS
840 Pro Caviar Black LG BD-ROM Windows 8.1 Pro x64 
MonitorMonitorKeyboardPower
Dell U2713HM Dell U2311H Turbo-Trak (Google it :D) Corsair HX-520 
CaseMouseMouse PadAudio
CM690 Mionix Avior 7000 Everglide Titan AKG K 242 HD 
  hide details  
Reply
    
CPUMotherboardGraphicsRAM
i7 920 D0 MSI X58 Pro-E GTX 560 Ti 448 3x2GB G.Skill DDR3-1333 9-9-9-24 
Hard DriveHard DriveOptical DriveOS
840 Pro Caviar Black LG BD-ROM Windows 8.1 Pro x64 
MonitorMonitorKeyboardPower
Dell U2713HM Dell U2311H Turbo-Trak (Google it :D) Corsair HX-520 
CaseMouseMouse PadAudio
CM690 Mionix Avior 7000 Everglide Titan AKG K 242 HD 
  hide details  
Reply
post #3 of 5
I would recommend using something similar to the following:
Code:
amt = Number(amount);
if (amt && (currency.toLowerCase() === "usd")) {
  //do stuff if USD
}else if (/*CAD tests here*/) {
  //do stuff if CAD
} else {
  //handle bad input
}

The toLowerCase ensures that all combinations ("Usd", "USd", "uSd", etc) are valid. The function/constructor Number() returns a string converted to a number else returns NaN. Note that Number() accepts exponentiated numbers (eg. "1.23e22") which is kind of interesting, but it also accepts NEGATIVE numbers, so you need to either error out on negative numbers or find their absolute value.


Also, NEVER use decimals for money. This can lead to rounding issues with floating point. Instead, multiply the number by 100 to keep cents as integers (in your case, multiply by 10,000). Do all your calculations as integers and only convert it back when you need to display the number somewhere.
post #4 of 5
Thread Starter 
Quote:
Originally Posted by hajile View Post

I would recommend using something similar to the following:


The toLowerCase ensures that all combinations ("Usd", "USd", "uSd", etc) are valid. The function/constructor Number() returns a string converted to a number else returns NaN. Note that Number() accepts exponentiated numbers (eg. "1.23e22") which is kind of interesting, but it also accepts NEGATIVE numbers, so you need to either error out on negative numbers or find their absolute value.


Also, NEVER use decimals for money. This can lead to rounding issues with floating point. Instead, multiply the number by 100 to keep cents as integers (in your case, multiply by 10,000). Do all your calculations as integers and only convert it back when you need to display the number somewhere.

Thanks alot! I have one more question on something else i was working on. Why does the else if statement not work in this bit of code? I'll type in letters and doesn't return the alert
Code:
function newGrade() {
        
        var grade = parseFloat(document.getElementById("currentGrade").value);
        var result = document.getElementById("result");
        
        if(( currentGrade.value > 0 || currentGrade < 100) ){
                result.value = ((currentGrade.value / 20) - 1).toFixed(2);
         }else if(currentGrade.value(isNaN)){
                 alert("Please enter a correct value!");
        }else{
                return;
        }
}
post #5 of 5
Quote:
Originally Posted by Ubeermench View Post

Thanks alot! I have one more question on something else i was working on. Why does the else if statement not work in this bit of code? I'll type in letters and doesn't return the alert
Warning: Spoiler! (Click to show)
Code:
function newGrade() {
        
        var grade = parseFloat(document.getElementById("currentGrade").value);
        var result = document.getElementById("result");
        
        if(( currentGrade.value > 0 || currentGrade < 100) ){
                result.value = ((currentGrade.value / 20) - 1).toFixed(2);
         }else if(currentGrade.value(isNaN)){
                 alert("Please enter a correct value!");
        }else{
                return;
        }
}

Your else-if statement isn't correct. Also note that isNaN() is broken in a few edge cases. You can do a similar check by seeing if a variable is NOT equal to itself.
Warning: Spoiler! (Click to show)
Code:
var x = NaN;

if (x !== x) {
  console.log('it's NaN');
}

In addition, OR statements ( || ) short circuit. For example: Warning: Spoiler! (Click to show)
Code:
var x = 5,
    y = 10;

//this will NEVER test y because x is always true
if (x === 5 || y < 5) {
  console.log("true");
}
//In your case, it sees y is greater than 0, so it never checks if it's less than 100

var y = 100000

if (y > 0 || y < 100) {
  console.log("true");
}

//it's worth noting that AND ( && ) also short-curcuits
//if it sees a false
var x = 5,
    y = 10;
if(x > 10 && y === 10) {
  //nothing ever happens and y is never checked
}

Short circuiting is something you are likely to see a lot in assignment. A classic example would be: Warning: Spoiler! (Click to show)
Code:
//I want y to be an optional parameter. If it's not added
//I want it to be 5
var myFunc = function (x, y) {
  //if y has a value (besides NaN, null, or undefined)
  //it will short-circuit before the value is changed to 5
  //otherwise, it will return 5 which is then assigned to y
  y = y || 5;
  return (x + y);

  //it's the same as this
  y = y ? y : 5;
  
  //or this
  if ( !y ) {
    y = 5;
  }
};

myFunc(4); //--> 9
myFunc(4, 9); //--> 13

You also see it in the AMD pattern (asynchronous module pattern). Ignore this if it's too advanced at the moment (if you don't know what closures are, it's probably too advanced).
Warning: Spoiler! (Click to show)
Code:
//first, here's a simple self-executing function
//the enclosing parens and the () at the end
//cause the function to call itself (even though we haven't given it a name)
(function () {
  console.log("this prints immediately");
}());

//this one takes two params and adds them together
(function (x, y) {
  console.log(x + y);//--> "50"
}(25, 25));

//we can also assign these self-executing functions to variables
var myModule = (function () {
  //do something
}());

//we want to make the module return something useful

var myModule = (function () {
  var x = {};
  var y = 25; //nobody will see this

  x.myvar = 5;//everyone will see this

  x.myFunc = function () {
    console.log("this is a basic function");
  }

  x.addY = function(w) {
    return (w + x.myvar);
  }

  //this assignes myModule to the value of X (which is our object)
  return x; 
}());

//we can now use myModule
myModule.myvar = 2; //changes x.myvar from 5 to 2
myModule.myFunc();//-->"this is a basic function"
myModule.addY(5);//--> 30 (since y is 25 inside our function)

//notice that you can't access the y inside the self-executing function
//you can only access whatever's inside of x (and then returned for use)

//what about if we split our module into parts? How can we put those together in the same variable?
//we do what we would do for a regular variable. For example, if we want to add to x
x = 5;
x = x + 5; 

//we are doing a similar thing here
var myModule = (function (modulePart) {
  //if we have already created myModule, we extend it
  //otherwise, we create a new one
  x = modulePart || {}; //this is the key
  x.newVar = "string";
  x.newFunc = function () {
    //do something
  }
  return x;
}(myModule));
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Web Coding