Currency Conversion (jQuery) - javascript

My currency converter is constantly outputting NaN, instead of the actual conversion.
Ex: If the user-entered US dollars is 100.00, Canadian Dollar (CAN) is elected, and the exchange rate is "CAD": 1.316853, the resulting converted currency is 131.69
I am tasked with the following:
Converts the user-entered US dollars to the selected currency using the rates listed in the exchangeRates object. Display the converted currency with two decimal digits.
Ex: If the user-entered US dollars is 100.00, Canadian Dollar (CAN) is elected, and the exchange rate is "CAD": 1.316853, the resulting converted currency is 131.69
Displays the resulting converted currency by updating the readonly <input> element with ID resultCurrency
Updates the associated label for resultCurrency to the selected currency's full currency name, currency abbreviation in parentheses, and colon
Ex: Canadian Dollar (CAN):
// Initial data for exchange rates
var exchangeRates = {
"disclaimer": "Usage subject to terms: https://openexchangerates.org/terms",
"license": "https://openexchangerates.org/license",
"timestamp": 1534107604,
"base": "USD",
"rates": {
"BTC": 0.000157753542,
"CAD": 1.316853,
"EUR": 0.879353,
"JPY": 110.46550427,
"USD": 1,
}
};
$(document).ready(function() {
// Function to update the options in the toCurrency dropdown
function updateToCurrencyOptions() {
// Get the select element and empty its current options
var $toCurrencySelect = $('#toCurrency');
// Add the first "Select currency" option
var $selectOption = $('<option>', {value: '', disabled: true, selected: true}).text('Select currency');
$toCurrencySelect.append($selectOption);
// Loop through each currency in the exchange rates object and add an option for it
for (var currency in exchangeRates.rates) {
// Get the currency abbreviation and full name
var abbreviation = currency;
var fullName = allCurrencies[currency];
// Create the option element and add it to the select element
var $option = $('<option>', {value: abbreviation}).text(fullName + ' (' + abbreviation + ')');
$toCurrencySelect.append($option);
}
}
// Function to convert USD to the selected currency and update the result input and label
function updateResultCurrency() {
// Get the amount in USD and selected currency from the inputs
var usd = $('#usdAmount').val();
var currency = $('#toCurrency').val();
// Convert the USD to the selected currency using the exchange rates object
var rate = exchangeRates.rates[currency];
var converted = usd * rate;
// Round the converted amount to 2 decimal places
converted = Math.round(converted * 100) / 100;
// Update the result input and label
$('#resultCurrency').val(converted.toFixed(2));
var fullName = allCurrencies[currency];
$('#resultLabel').text(fullName + ' (' + currency + '):');
}
// Function to update the exchange rates and dropdown options when the Update Rates button is clicked
function updateExchangeRates() {
// Get the new exchange rates from the textarea and parse them as JSON
var newRatesJson = $('#exchangeRates').val();
var newRates = JSON.parse(newRatesJson);
// Update the exchange rates object and the dropdown options
exchangeRates = newRates;
updateToCurrencyOptions();
// Reset the result input and label
$('#resultCurrency').val('---.--');
$('#resultLabel').text('To Currency ():');
}
// When the page is ready, update the dropdown options and set up the event listeners
updateToCurrencyOptions();
$('#toCurrency').change(updateResultCurrency);
$('#updateRatesButton').click(updateExchangeRates);
});

Related

I'm trying to format a number in apps script that will return the users negative input with -£3.50 instead of £-3.50

I'm trying to format a number in apps script that will return the users negative input with -£3.50" instead of £-3.50, however, my code doesn't seem to work, I'm using a google spreadsheet for this, can anyone help me with this?
var ui = SpreadsheetApp.getUi();
var snacks = ui.prompt('Numbers only.', 'Please enter the price of the snacks.', ui.ButtonSet.OK);
var snacksPrice = snacks.getResponseText();
if (snacksPrice = "-") {
snacksPrice = snacksPrice.toFixed(2);
snacksP = snacksPrice.split("");
ui.alert(snacksP[0] + "£" + snacksP[1] + snacksP[2] + snacksP[3]);
}
you can use the javascript Intl.NumberFormat method for formatting numbers. The Intl.NumberFormat object enables language-sensitive number formatting.
now, I've refactored your code so that you can understand what has changed.
var ui = SpreadsheetApp.getUi();
// here I'm basically creating a new `numberFormat` instance.
// your currency is pounds `£`, therefore you need to put currecy value as *GBP*
const nf = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' })
var snacks = ui.prompt('Numbers only.', 'Please enter the price of the snacks.', ui.ButtonSet.OK);
// use parseFloat to convert string to number. e.g. '-11.2' -> -11.2
var snacksPrice = parseFloat(snacks.getResponseText());
ui.alert(nf.format(snacksPrice));
Here is a basic example:
const yourNumber = -100
const nf = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' })
console.log(nf.format(yourNumber))
if you need to know more about it, please check out mdn documantation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat

The Currency Converter in 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);

Adding percentage to a price field incl. currency code

I'm trying to add 10% to a price field via javascript and so far i haven't been able to, and was hoping you guys would be able to help.
The field incl. currency code etc.
I did try something in this direction:
<script type="text/javascript">
$( document ).ready(function() {
var Total = $("#cashamount");
Total.val(Total.val() * 1.1);
});
</script>
But that didn't work ;(
The price field shows up like the following.
<span id="cashamount" class="additional xxlarge carrental_total_amount">48,300.00 ISK</span>
After adding the 10% to the price, it should say in this example:
<span id="cashamount" class="additional xxlarge carrental_total_amount">53,130.00 ISK</span>
Any ideas are welcome, and i would really appreciate help on this matter as i do think it's fairly simple but i'm not very well into Javascripting.
First this: (solution below)
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the
.val() method returns an array containing each selected option; if no
option is selected, it returns null, jQuery docs
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method,
jQuery docs
So, one solution would be next:
var Total = $("#cashamount");
var totalNumber = Number(Total.text().replace(/[^0-9\.]+/g,""));
Total.text((totalNumber * 1.1).toFixed(2));
//Add currency to this
Here's JsFiddle
var x = $("#cashamount").html(); // Fetching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
$("#cashamount").html(y); // Setting the html;
So you can create a function for this:
function updateVal(elem){
var x = elem.html(); // Fethching the value
var xSplit = x.split(" "); // Splitting the currency and ammount and storing it in array.
var intAmmt = +xSplit[0].replace(/,/g , ""); // Removing comma and Making it a integer
var newAmmt = intAmmt*1.1; // Incrementing by 10%
var y = newAmmt.toLocaleString() + " " + xSplit[1]; // Adding the currency sign with a space
elem.html(y); // Setting the html;
}
and use it as:
$(document).ready(function(){
updateVal($("#cashamount"))
});

Using jQuery / JS to switch form values fails when value contains a '/'

I'm using a switch function with a unit converter that allows a user to swap units instead of changing their selection. It works fine then I noticed that in some cases it failed.
I went through all the options until reducing the size of the value field/ It then worked. I assumed that the value was too long but after checking on here:
Max length of an HTML attribute value
it looks like I was well within the boundaries. So I'm wondering what else it could be?
Below are two examples taken from the console log showing Before and After the switch button was pressed and the results once I changed the name.
Measurement Type: thermalExpansion
convertFunctions.js:30BEFORE!!! from: length/length/degreeC to: length/length/degreeRan
convertFunctions.js:40AFTER!!! from: length/length/degreeC to: length/length/degreeRan
convertFunctions.js:1020Parsed input is 1 and result is 0.555555556
Measurement Type: thermalExpansion
convertFunctions.js:30BEFORE!!! from: lengthRan to: lengthk
convertFunctions.js:40AFTER!!! from: lengthk to: lengthRan
EDIT: I just tested again using the oblique in the field and it failed.
EDIT AGAIN: More Info:
The function, shows where the console logs were generated
function switchUnits(){
//need to get values before swap to and from around.
var from = $("#from").val();
var to = $("#to").val();
console.log('BEFORE!!! from: ', from, 'to: ', to );
//switches the details
$("#to #"+from).attr("selected","selected");
$("#from #"+to).attr("selected","selected");
//gets values after switch
from = $("#from").val();
to = $("#to").val();
console.log('AFTER!!! from: ', from, 'to: ', to );
//run convert
convertUnits();
}
Example of the JSON file once edited to remove all '/' from the value field
Before edit example:
"thermalExpansion":[
{
"value": "length/degreek",
"name" : "Length / Length / Kelvin (1/K)"
},
],
After edit example:
"thermalExpansion":[
{
"value": "lengthk",
"name" : "Length / Length / Kelvin (1/K)"
}
],

jQuery/Javascript splitting string calculation

I'm creating a product page that requires the price to update when the quantity value is changed. Two form fields are used: .orig_price and #quantity. These values are obviously multiplied together.
I'm trying to split the multiplied value, so that I can print the correct format (27.7043454575 should be 27.70).
My code:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = jQuery(".orig_price").val().substr(1);
var qty = jQuery("#quantity").val();
// calculate price
var sumValue = origprice * qty;
// split price
var splitprice = sumValue.split(".");
var pricepound = splitprice[0];
var pricepenny = splitprice[1].substring(0,2);
// update price
jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
jQuery("#pricediv").fadeIn(1500);
});
If I remove the split and use sumValue everything works (but format is wrong). Does split not work on a calculation?
You'll want to use sumValue.toFixed(2)
var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70
.split does not exist on numeric types. You would have to use sumValue.toString().split('.'), and either way, this would be more inconvenient than simply sticking to .toFixed
You can use toFixed and parseInt() like so:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = parseInt(jQuery(".orig_price").val().substr(1),10);
var qty = parseInt(jQuery("#quantity").val(),10);
// calculate price
var sumValue = origprice * qty;
// split price
var price = sumValue.toFixed(2);
// update price
jQuery("#pricediv").html('£' + price);
jQuery("#pricediv").fadeIn(1500);
});
toFixed determines the number of points after a decimal, and parseInt type-casts the input to an integer (the 10 is unnecessary but there to show it's decimal base 10), because when getting data from a form field it sometimes comes back as a string and messes up your math.

Categories

Resources