Joseph Michael Pesch
VP Programming

JavaScript Issue with Decimal Values

by 20. April 2010 16:43

Doing simple math, such as subtracting two decimal values, can result in strange decimal values (make sure to use the Math.round function to set the desired decimal places on the final outcome) as outlined in the below sample:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

  <title></title>

</head>

<body>

 

 

  <script language="javascript" type="text/javascript">

    function Subtract() {

      alert(parseFloat(document.getElementById("txt1").value));

      alert(parseFloat(document.getElementById("txt2").value));

      var thirdVal = 0;

      thirdVal = parseFloat(document.getElementById("txt1").value) - parseFloat(document.getElementById("txt2").value);

      alert(thirdVal);

      document.getElementById("txt3").value = Math.round(thirdVal * 100) / 100;

    }

  </script>

 

 

  <form id="form1" runat="server">

  <div>

    first Param:

    <input type="text" id="txt1" value="47389.10" />

    Second Param:

    <input type="text" id="txt2" value="14216.73" />

    Result:

    <input type="text" id="txt3" value="" />

    <input type="button" onclick="Subtract()" id="subtract" value="calculate" />

  </div>

  </form>

</body>

 

</html>

 

 

 

Tags:

[None]

Comments are closed