Ad

Simple Currency Conversion In Javascript

- 1 answer

I'm trying to get a currency conversion working.

I have built a data set:

const currencyRates = { USD:1.102539, EUR:1, GBP:0.84329691, AUD:1.61545337,JPY:120.4893208, CAD:1.44956315, CHF:1.07099756 }

This is my function so far.. but its still not working right :/

 function currencyConversion (from, to, val) {
    return ~~( (+val) * (currencyRates[to] + (1 - currencyRates[from])) )
  }

I have create a set of tests


  function test(from, to, val, result){
    const output = currencyConversion(from, to, val)
    return output === result ? ["✔",from, to] : ["✘",from, to,output,result]
  }

  console.log(test("USD","AUD",1000,1465))
  console.log(test("EUR","USD",1000,1102))  
  console.log(test("EUR","EUR",1000,1000)) 
  console.log(test("EUR","GBP",1000,0843))  
  console.log(test("EUR","AUD",1000,1615))
  console.log(test("USD","EUR",1000,907))  
  console.log(test("USD","USD",1000,1000))  
  console.log(test("JPY","USD",1000,9))
  console.log(test("GBP","EUR",1000,1185)) 
  console.log(test("AUD","EUR",1000,619))
  console.log(test("USD","GBP",1000,764))  
  console.log(test("GBP","AUD",1000,1915))
  console.log(test("AUD","USD",1000,682))
  console.log(test("AUD","JPY",1000,74579))
Ad

Answer

try this:

function currencyConversion(from, to, val) {
    return ~~(val / currencyRates[from] * currencyRates[to]);
}
Ad
source: stackoverflow.com
Ad