I encountered this weird anomaly creating a simple javaScript demo that I am going to use to teach my 11 year old the basics of coding. I think that perhaps I didn't sanitize the input strings before I used the javaScript parse float javaScript function. The program works fine for other floating point decimals ie. 2.5 + 3 = 5.5. However in this one instance 1.445 + 2 = 3.4450000000000003. Purely out of curiosity I would like to know what is going on here. So with out any further delay, here's the JavaScript code:
var funct = null;
function clarifyOperation(x)
{
if(x=="add")
{
document.getElementById("operation").innerHTML=" + ";
funct="add";
}
else if(x=="subtract")
{
document.getElementById("operation").innerHTML=" - ";
funct="subtract";
}
else if(x=="multiply")
{
document.getElementById("operation").innerHTML=" × ";
funct="multiply";
}
else if(x=="divide")
{
document.getElementById("operation").innerHTML=" ÷ ";
funct="divide";
}
}
function solve()
{
var x=document.getElementById("inputX").value;
var y=document.getElementById("inputY").value;
var z;
if(funct=="add")
{
z=parseFloat(x)+parseFloat(y);
document.getElementById("result").value=z;
}
else if(funct=="subtract")
{
z=parseFloat(x)-parseFloat(y);
document.getElementById("result").value=z;
}
else if(funct=="multiply")
{
z=parseFloat(x)*parseFloat(y);
document.getElementById("result").value=z;
}
else if(funct=="divide")
{
z=parseFloat(x)/parseFloat(y);
document.getElementById("result").value=z;
}
}
Here is the HTML code:
<input type="text" value="" id="inputX"/>
<span id="operation"> </span>
<input id="inputY" type="text" value="" />
<span> = </span>
<input type="text" value="" id="result" /><br />
<input type="radio" name="operation" value="add" onchange="clarifyOperation(this.value)" />
<span>+</span><br />
<input type="radio" name="operation" value="subtract" onchange="clarifyOperation(this.value)" />
<span>-</span><br />
<input type="radio" name="operation" value="multiply" onchange="clarifyOperation(this.value)" />
<span>×</span><br />
<input type="radio" name="operation" value="divide" onchange="clarifyOperation(this.value)" />
<span>÷</span><br />
<input type="button" value="calculate" onclick="solve()" />
<hr />
Reminder to the community: keep your comment's useful.