Javascript, weird floating point number endless decimal?
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()
:
var num = 45.34343434343;
num = num.toFixed(2); // "45.34"
Use the .toFixed()
function in Javascript.
document.getElementById("answer").value = (parseFloat(document.getElementById("num1").value) - parseFloat(document.getElementById("num2").value)).toFixed(2);
Or an easier to see version:
var x = 3.14159265358979323;
alert(x.toFixed(2)); // 3.14
A very good description of how it works on MDN.
See here there is a function Number.toFixed(num)
that do just that.
See more info and other options at W3Schools JS Numbers.
That problem occurs because in Javascript every Number
is 64bit floating-point, there no such thing as an Integer
.
The .toFixed()
is useful, but be ware that correctly rounding number in Javascript (and many other languages) require more work.
There are different rounding rules for "Tie-Breaking" and you need to know what is the one you need because they are used in different scenarios. Look here.
精彩评论