The Currency Converter in Javascript - javascript

I am trying to complete this exercise:
Ask the user how much money they have.
Next, ask them what currency they have
Finally, ask them what they want to convert it into
Convert the currency to the requested output
Print a nice alert message with the value in the other currency
Your code must use a minimum of two functions.
One function should calculate the conversion.
One function should print the alert message with the converted currency and the currency name.
Hint - It probably makes sense to use two conversion functions. One function to convert from any currency into USD and another to convert from USD into anything other currency.
Here is my code:
When I run the code in my browser nothing happens.
I'm not to true if I'm calculating the conversion right and when I run this nothing prints out.
UPDATE:
okay, I fix the problem so it's running now but I'm still not getting the function converting part
'use strict';
let money = Number(prompt("How much money do you have?."));
let moneyCurrency = prompt("What currency are you using?.");
let currencysys = prompt("What currency do you want to convert it to? EUR, JPY, GBP, USD, or BRL");
function convertCurrency(currency, currencySystem) {
if (currencySystem === 'JPY' || currencySystem === 'jpy') {
return convertJPYtoUSD(currency);
}
else if (currencySystem === 'Eur' || currencySystem === 'eur') {
return convertEurtoUSD(currency);
}
else if (currencySystem === 'GBP'|| currencySystem === 'gbp') {
return convertGBPtoUSD(currency);
}
else if ( currencySystem === 'BRL'|| currencySystem === 'brl') {
return convertBRLtoUSD(currency);
}
}
function convertJPYtoUSD(JPY) {
return (JPY * 0.91);
}
function printCurrencyMessage(convertedCurrency, currencysys,round) {
if (round === undefined || isNaN(Number(round))) {
round = 0;
}
}
console.log("The converted currency is "+currencySystem + ".");
update 2 :
I having a bit of trouble, The math code isnt right 100GBP to JPY should be 19,103.08 but I'm getting something completely different
'use strict';
let money = Number(prompt("How much money do you have?."));
let moneyCurrency = prompt("What currency are you using?.");
let currencysys = prompt("What currency do you want to convert it to? EUR, JPY, GBP, USD, or BRL");
`let currentExchange = {
"USD": 1,
"EURO" : 0.91,
"JPY" : 124.17,
"GBP" : 0.65,
"BRL" : 3.51,
}`
`let currentExchanges=currentExchange[currency];`
`function convertCurrency( currencyNeeded, moneyAmount) {
let exchange_value = moneyAmount * exchange_factor
return exchange_value
function convertCurrency( currencyNeeded, moneyAmount) {
let exchange_factor = currentExchange[currencyNeeded];
let exchange_value = moneyAmount / exchange_factor
let value = moneyAmount * exchange_factor
console.log("The converted amount is $ " + (exchange_value.toFixed(2)) + "in " + currencyNeeded+ ".");
return exchange_value
};
convertCurrency(currencyNeeded, moneyAmount);

TDLR;
You are trying to alert a variable that is not defined.
I would suggest you have your function return your value for you. Something like:
console.log("The converted currency is "+ convertToCurrency(moneyCurrency, currencysys + ".");
Explanation and digging deeper
Your signature
function convertCurrency(currency, currencySystem) {...
creates a local variable "currencySystem" that cannot be referenced outside of the functions scope. Hence, currencySystem is a local variable to that function.
Some general code/architecture suggestions:
Make variable names more meaningful and consistent.
Create a hashmap/object with all of your currency conversion ratios and use a single function to do the mathematical conversion. IE:
var currencies = {
usd: {
conversion: 1,
},
eur: {
conversion: .89
},
...
};
function convertCurrency(fromCurrency, toCurrency, amount) {
// ... not the best at thinking of the algorithm. Suggestions?
// perhaps normalize fromCurrency to the dollar, then convert to toCurrency since I believe the dollar is the base/universal currency
};
var convertedCurrency = convertCurrency("USD", "EUR", 20.50);
alert("The converted amount is" + convertedCurrency);
If you need multiple functions as a requirement, splitting out into each currency conversion isn't a horrible idea, but seems like a bit much overhead.
Here is a final working solution:
'use strict';
let amount = Number(prompt("How much money do you have?."));
let currentCurrency = prompt("What currency are you using?");
let desiredCurrency = prompt("What currency do you want to convert it to? EUR, JPY, GBP, USD, or BRL");
var currencyRates = {
"USD": 1,
"EUR": .8,
"JPY": .7,
"XXX": 5
};
function convertCurrency(currentCurrency, desiredCurrency, amount) {
var currentRate = currencyRates[currentCurrency];
var desiredRate = currencyRates[desiredCurrency];
var USDAmount = amount * currentRate;
var convertedAmount = USDAmount / desiredRate;
return convertedAmount; // I think this is the right algorithm :/
}
var convertedCurrencyAmount = convertCurrency(currentCurrency, desiredCurrency, amount);
alert ("Converted: " + convertedCurrencyAmount);

Related

how to truncate output values in Nerdamer

I am using nerdamer.solve to solve roots but the roots are long and not truncated. I wanted to get truncated values upto 4 decimal places. How can I achieve this?
I am using the following code to solve and display output in html:
var r = nerdamer.solve(`1 - ${a} * x^(${p}) + ${b}`, 'x');
document.getElementById("polesAns").innerHTML= r.toString();
The folllowing is output:
[(138655807/135201312)*i+49385501/48155102,(-138655807/135201312)*i+49385501/48155102,(58886197/57419096)*i-49385501/48155102,(-58886197/57419096)*i-49385501/48155102,-560373381/386371730,172668482/119053157,(145619303/100403024)*i-5753750945848186/10000000000000000000000000000000,(-560373381/386371730)*i-5753750945848186/10000000000000000000000000000000]
There is no division performed also.
I tried the solution posted here:
How to use .toFixed() (or any alternative) on Nerdamer.solve solutions?
But how can I do this with my code? I tried the following:
var value = `1 - ${a} * x^(${p}) + ${b}`;
var toFixed = function(value, n) {
var img = Number(nerdamer.imagpart(value).text()).toFixed(n);
var real = Number(nerdamer.realpart(value).text()).toFixed(n);
// Format the number assuming i denotes imaginary in your case
var formatted = '';
if(real !== '0.0000') {
formatted += real;
}
if(img !== '0.0000') {
// Put the plus sign betweent the real and imaginary
if(img.charAt(0) !== '-' && formatted) {
formatted += '+';
}
// Assuming you're using i and not j for instance
formatted += img+'i';
}
return formatted;
};
sol_raw = this.nerdamer.solve(value,'s');
xs = this.nerdamer(sol_raw.toString()).each(function(solution) {
roundedSolutions.push(toFixed(solution, 4));
});
this.setState({
solution: roundedSolution.join(''),
equation:value})
document.getElementById("polesAns").value = solution.toString();
I don't understand the this.setState() part , should i declare sol_raw and xs as var?
Also the substitution of variable is used in the my above root equation from advice here javascript Solving equation with subsitution of variable value
thank you

Do loop with a switch case in javascript

//I need to add one to the total each time the error name is input. For example if I type "S" in the prompt, then it will add 1 to the total steering and if I type "W", it will add to wiper. The loop should run until i entered a null or zero value and calculate the total errors.
<html>
<head><title>Charge Calculator</title></head>
<body>
<script type="text/javascript">
//Declaring Variables
var day;
var data="";
var steering = 0;
var turbo =0;
var wiper =0;
day = prompt("Enter day: ","");
var BR="<br/>";
do
{
data = prompt("Enter Data: ","");
data = input.nextLine();
switch(data)
{
case 'S':
steering++;
break;
case 'T':
turbo++;
break;
case 'W':
wiper++;
break;
}
}
while(data == "")
document.write("day: " +day +BR); //Display destination name
document.write("Steering issue: " +steering +BR);
document.write("turbo Issue: " +turbo +BR);
document.write("wiper Issue: " +wiper +BR);
</script>
</body>
</html>
There are many things to be improved in your code. Be aware that the write() expression will potentially destroy parts of your html-based page. Find out about DOM manipulation commands instead.
The following snippet demonstrates in a very short way how you could collect your inputs. I used your prompt() method simply to show that it can be done but I would always prefer a simple input field instead.
const counts={s:0,t:0,w:0};
while (++counts[prompt("Please enter the error type code (s,t or w):").toLowerCase()]) {}
console.log("steering: "+counts.s+
"\nturbo: "+counts.t+
"\nwipers: "+counts.w);
Everything happens within the expression that calculates the result for the while condition: the input value is converted to lower case and then a property of the object counts will be incremented. This will only work (= return a "truthy" result) for already initialised properties like s, t or w. For all other cases an increment cannot be calculated, resulting in an "NaN" ("not a number") result. This will then end the while loop.
Seems like recursion could be more appropriate solution here. Though #Cartsten's one looks absolutely ok also.
function count() {
const counts = {
s: 0,
t: 0,
w: 0
};
const checkCounts = () => {
let input = prompt(
'Please enter the error type code (s,t or w):'
).toLowerCase();
if (counts[input] !== undefined) {
++counts[input];
return checkCounts();
}
};
checkCounts();
console.log(
`steering: ${counts.s} \n turbo: ${counts.t} \n wipers: ${counts.w}`
);
}
count();

Javascript: parseInt issue when it comes to math operators

I have this slider that on 'slide' grabs pricing values (string with euro symbol) from an array, later parsed (parseInt) for the html output. This works fine, on the output i get the number plus the symbol, but when I need to multiply those values (switch month pricing to anual), I loose the output, no numbers or symbol. So I guess the parseInt is working properly without a math operator...? I've serached for similar issues but I couldn't find any solution and it just got me more confused...Can anyone tell what I'm missing? The code:
var priceStarter = [
'149€',
'199€',
'249€',
'399€',
'599€',
'999€',
'Contact Us',
];
slider.on('slide', function (values, handle) {
if(jQuery(this).hasClass('active-anual')){
//ANUAL
var anualStarter = priceStarter[parseInt(handle)];
priceValueStarter.html(anualStarter * 10); //ISSUE HERE
}
else {
//MONTHLY
priceValueStarter.html(priceStarter[parseInt(handle)]); //WORKS
}
});
//TOGGLE ANUAL/MONTHLY
anual.on('click',function(){
jQuery(this).toggleClass('active-tab');
monthly.removeClass('active-tab');
slider.addClass('active-anual');
})
monthly.on('click', function () {
jQuery(this).toggleClass('active-tab');
anual.removeClass('active-tab');
slider.removeClass('active-anual');
})
}
EDIT:
This console.log(anualStarter) gives me the correct value but this console.log(anualStarter*10) gives me NaN
EDIT: based on Constantiner's answer, I get the numbers but I still loose the euro symbol and the contact us when using the operator
slider.on('slide', function (values, handle) {
if (jQuery(this).hasClass('active-anual')) {
//ANUAL
var anualStarter = priceStarter[parseInt(handle)];
priceValueStarter.html(parseInt(anualStarter )*10);
} else {
//MONTHLY
priceValueStarter.html(priceStarter[parseInt(handle)]);
}
})
;
Your priceStarter[parseInt(handle)] is a string like "249€". So you can't use anualStarter * 10 ("249€" * 10) — it is NaN. Try to use parseInt(anualStarter) * 10 instead.
A little explanation. When you try to use "249€" * 10 JavaScript engine tries to cast the string "249€" as a Number and doesn't interpret it as integer or something. So your "249€" * 10 is the same as Number("249€") * 10 and Number("249€") is NaN.
I suppose you planned to write some code like the following:
slider.on('slide', function (values, handle) {
if(jQuery(this).hasClass('active-anual')){
//ANUAL
var anualStarter = priceStarter[parseInt(handle)];
priceValueStarter.html(isNaN(parseInt(anualStarter)) ? anualStarter : parseInt(anualStarter) * 10 + "€"); //ISSUE HERE
}
else {
//MONTHLY
priceValueStarter.html(priceStarter[parseInt(handle)]); //WORKS
}
});

Regarding decimal in javascript

When i am writing 11.00 it is displaying 11.00.00 otherwise its working fine on rest
if(pos == -1)
{
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount + ".00";
}
else
{
var integer = enterCheckAmount.substring(0,pos);
var decimals = enterCheckAmount.substring(pos+1);
while(decimals.length<2) decimals=decimals+'0';
enterCheckAmount = integer + '.' + decimals;
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount;
}
JavaScript doesn't have a variable type for decimal numbers. It has only Number. If you want to display an integer as a decimal number with two zeros after the decimal point you can use the method toFixed.
Here is an example:
var myNumber = 11;
var myDecimalNumber = myNumber.toFixed(2);
console.log(myDecimalNumber) // will output 11.00
Thus there is no need to concatenate strings and add ".00" manually to your number.
Beyond this you can use the methods parseInt and parseFloat. Let's say you have a variable of type string with the value "11 pieces". You can get the integer with this line of code:
var myString = "11 pieces";
var myInteger = parseInt(myString, 10);
console.log(myInteger); // will output 11
If you have something similar like this, you are better off with this methods instead of cuting substrings.
I wish you a lot of success in refactoring your code and a warm welcome to the StackOverflow community.

Javascript : function checking if the answer to score as a percentage has more than 2 decimal places

I want to create a dynamic worksheet for my students, so every time they do it they see different questions. The question that I am trying to create ie, calculate the percentage if I scored X out of a total of Y.
Here are the 3 functions which work together, the first generates some numbers, calls the second, which in turn calls the third to check if it more than 2 decimal places, then if it is, the second creates a new SCORE number which repeats until it finds an answer which is 2 decimal places or less, then returns the SCORE number which works to the first, which outputs it.
I keep getting one of three outputs : undefined where the SCORE should be, no output at all, or a working question.
I cannot understand how it works sometimes, throws undefined sometimes and gives completely nothing at other times.
Any ideas.
function scorePercent()
{
var output="";
var total = Math.floor((Math.random()*99)+1);
var score = Math.floor((Math.random()*(total-1))+1);
output = output + "<div>A score of " + chkScore(score,total) + " out of " + total + ".</div></br>";
document.getElementById("qOut").innerHTML=output;
}
function chkScore(n1,n2)
{
var answ = (n1/n2)*100;
if(dps(answ)>2)
{
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
chkScore(scoreNew, n2);
}
else
{
return n1;
}
}
function dps(num)
{
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
You have a recursive function in your chkScore, but you're not return-ing the results from the "deeper" iterations.
Try this:
function chkScore(n1,n2){
var answ = (n1/n2)*100;
if(dps(answ)>2) {
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
return chkScore(scoreNew, n2); // <-- return that.
} else {
return n1;
}
}
The missing return there, resulted in the function sometimes not returning anything.
The "deeper" iterations will return their value only 1 "level" up, so that "level" will have to pass it through, if you know what I mean.

Categories

Resources