Click here to Skip to main content
15,896,542 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
Here is my code. if you enter 12 / 88 you get 7.3333333333333333
I want any division to be only 2 decimals long but can't seem to find the correct way. I want to have the result in my TextBoxAvgTimeMedRec field.

XML
<script lang='text/javascript'>
  function Calculate()
  {
    if ( (document.getElementById('<%= TextBoxNumPatInt.ClientID%>').value != " ") && (document.getElementById('<%= TextBoxNumMinDoc.ClientID%>').value != " ") )
    {
        document.getElementById('<%= TextBoxAvgTimeMedRec.ClientID%>').value = parseFloat(document.getElementById('<%= TextBoxNumMinDoc.ClientID%>').value) / parseFloat(document.getElementById('<%= TextBoxNumPatInt.ClientID%>').value);
    }
  }
</script>
Posted

User toFixed function for this:

parseFloat("12.344343").toFixed(2)
 
Share this answer
 
Comments
Krunal Rohit 2-Oct-15 0:35am    
5!
-KR
You can either use Math.round or toFixed to limit decimal places. Here is the script:

C#
var a = 12;
var b = 88;
var c = a/b;
alert( Math.round(c * 100) / 100 );
alert(c.toFixed(2));
 
Share this answer
 
v2
Comments
Krunal Rohit 2-Oct-15 0:35am    
5!
-KR
You can use .toFixed()[^] here to get the desired output and also use a generic function to reuse the code again like:

JavaScript
function Calculate() {
    var textBoxNumPatInt = document.getElementById('<%= TextBoxNumPatInt.ClientID%>').value;
    var textBoxNumMinDoc = document.getElementById('<%= TextBoxNumMinDoc.ClientID%>').value;

    if ((textBoxNumPatInt !== "") && (textBoxNumMinDoc !== "")) {
        var newValue = GetDecimalValue(textBoxNumMinDoc) / GetDecimalValue(textBoxNumPatInt);
        document.getElementById('<%= TextBoxAvgTimeMedRec.ClientID%>').value = GetDecimalValue(newValue);
    }
}

function GetDecimalValue(value) {
    return (value ? parseFloat(value).toFixed(2) : 0.00);
}


Hope this helps!
 
Share this answer
 
v3

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