I need some help with floating point numbers…please!
Here’s the thing, I have code like below:
<script>
function add()
{
document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) + parseFloat(document.getElementById("num2").value);
}
function subtract()
{
document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) - parseFloat(document.getElementById("num2").value);
}
function multiply()
{
document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) * parseFloat(document.getElementById("num2").value);
}
function divide()
{
document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) / parseFloat(document.getElementById("num2").value);
}
</script>
Sorry it’s a bit long! And then the html is pretty simple:
<h1>Calculator</h1>
<h3>Enter a value in each box below, then click an operation</h3>
<form id="calculatorForm">
<input id="num1" value="0" type="text">
<input id="num2" value="0" type="text">
<br>
<input value="+" onclick="add();" type="button">
<input value="-" onclick="subtract();" type="button">
<input value="*" onclick="multiply();" type="button">
<input value="/" onclick="divide();" type="button">
<br>
<input id="answer" value="0" type="text">
</form>
You can pretty much guess what my question is gonna be: when I multiply, divide, or subtract two floating point numbers, I end up with an infinite decimal.
I need a quick solution that will round those numbers to two decimal points, and I need it to work later on, because I then need to implement Fahrenheit-to-Celsisus operations afterwards.
I don’t care how this is done, but it must be Javascript. Sorry if this has been answered before, but I really need an answer soon! Thanks!
EDIT: A BIG Thankyou to the helpful people who answered my questions. Thank you!
Use
.toFixed():