I've tried searching Google but I can't get any of the suggestions I find to fit into my code: <SCRIPT> window.onload = function() { var myForm = document.getElementById("theForm"); myForm.onsubmit = function() { var n1 = document.getElementById("num1").value; var n2 = document.getElementById("num2").value; var n3 = document.getElementById("num3").value; document.getElementById("result").innerHTML = n1 / n3 * n2 * 4.6 / 10; return false; } } </SCRIPT> Code (markup): How do I get the result of document.getElementById("result").innerHTML = n1 / n3 * n2 * 4.6 / 10; to only display to 2 decimal places?
first of all, you need to typecast the data to a numeric / interger or you will get errors. use parseInt(value, 10); // radix 10. second, Math.round(value, decimals); myForm.onsubmit = function() { var n1 = parseInt(document.getElementById("num1").value, 10); // 10 base radix to avoid errors when entry like 08 in field. var n2 = parseInt(document.getElementById("num2").value, 10); var n3 = parseInt(document.getElementById("num3").value, 10); document.getElementById("result").innerHTML = Math.round(n1 / n3 * n2 * 4.6 / 10 * 100) / 100; return false; } Code (javascript):
Okay, after being inspired by what you posted I looked around and altered my code a little to make this which works: <SCRIPT> window.onload = function() { var myForm = document.getElementById("FuelSave"); myForm.onsubmit = function() { var n1 = parseInt(document.getElementById("num1").value, 10); // 10 base radix to avoid errors when entry like 08 in field. var n2 = parseInt(document.getElementById("num2").value, 10); var n3 = parseInt(document.getElementById("num3").value, 10); var n4 = n1 / n3 * n2 * 4.6 / 10; document.getElementById("result").innerHTML = n4.toFixed(2); return false; } } </SCRIPT> Code (markup):
multiply the number by 100, take the parseInt of it and then divide the number 100 after taking parse float of it