Click here to Skip to main content
15,905,504 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is my code that works perfect except I need to have the third textbox limit the answer to 2 decimal places. I have tried to insert the toFixed value but I can't seem to find the right way to insert it.
My textbox 2 has the onblur="Calculate()" in its html code so that it triggers the calculation for the textbox 3 input but I get too many decimal places.

C#
function Calculate() {
            var t1 = parseFloat(document.getElementById('<%= TextBoxTotalScoreAnc.ClientID%>').value);
            var t2 = parseFloat(document.getElementById('<%= TextBoxPossibleScoreAnc.ClientID%>').value);

           document.getElementById('<%= TextBoxOverallScoreAnc.ClientID%>').value = t1 / t2 * 100 + '%';
        }
Posted

Please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed[^],
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision[^].

Now, a big warning for you: avoid using Math.round. In 99.9999(9?)% of the cases, you don't need rounding anywhere except the final string you show on screen. At the same time, you can, by some reason, use rounding on some intermediate results, and get critical precision loss in final results. This is a typical mistake of some beginners.

—SA
 
Share this answer
 
Rather I'd use .toFixed()[^] method from jQuery.
JavaScript
var n = 2.5689;
alert(n.toFixed(2));
//ouput 2.56


-KR
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900