Reputation: 21
This is my first JS script. It's a currency calculator and I have a problem with it.
The code produces the value of the new currency after the user inserts the amount, the exchange rate and the currency. However, it gives a return like this
8.100000000000001.
I have been reading about Number.toFixed(x) and Number.toPrecision(x) but I have no idea where to put them in my code, or even if this is the best way to do it.
Please would somebody advise me, code below.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Currency Converter</title>
<script>
//Gets Values from TextBox
var number1, exchangeRate, result;
function setValues() {
number1 = Number(document.getElementById("number1").value);
exchangeRate = Number(document.getElementById("exchange-rate").value);
}
//Calculates Values from TextBox
function calculate() {
setValues();
result = number1*exchangeRate;
document.getElementById("answer").innerHTML = result;
}
//Prints the selected currency
function printCurrency() {
var myCurrency = document.getElementById("myCurrency").value;
document.getElementById("print-currency").innerHTML = myCurrency;
}
</script>
</head>
<body>
<table>
<tr>
<td>
Insert Amount <input type="text" id="number1">
</td>
<td>
Exhange Rate <input type="text" id="exchange-rate">
</td>
<td>
Select currency
<select id="myCurrency">
<option value="USD">USD</option>
<option value="GPB">GBP</option>
<option value="EUR">EUR</option>
<option value="VND">VMD</option>
<option value="KHR">KHR</option>
</select>
</td>
<td>
<input type="button" onclick="printCurrency(); calculate()" value="Calculate">
</td>
</tr>
</table>
<p>Your amount is: <span id="print-currency"></span> <span id="answer"</span></p>
</body>
</html>
Upvotes: 0
Views: 2465
Reputation: 946
Modify function calculate as :
function calculate() {
setValues(); result = number1*exchangeRate; document.getElementById("answer").innerHTML = result.toFixed(2);
}
Upvotes: 0
Reputation: 23768
Apply it to your result.
document.getElementById("answer").innerHTML = result.toFixed(2);
In JS you can apply these functions to any number.
var a = 8.100000000000001;
console.log(a.toFixed(2));
Upvotes: 3