1. Member
Join Date
Dec 1969
Posts
32

Hi Friends:<BR>i am using the following code for calculation using javascript, its giving wrong result (i.e. 2.52000000000003, whereas it should only give 2.52 as result)..<BR><BR>plz help.<BR><BR>here is the source code:<BR><BR>&#060;html&#062;<BR>&#060;head&#062;< BR><BR>&#060;title&#062;JavaScript&#060;/title&#062;<BR> <BR>&#060;script language="javascript"&#062;<BR><BR>function Calculate() {<BR> <BR> var a = eval(42.52)<BR> var b = eval(40)<BR> var c = eval(a)-eval(b)<BR> alert(c);<BR><BR>}<BR><BR>&#060;/script&#062;<BR><BR>&#060;/head&#062;<BR><BR>&#060;body&#062;<BR><BR>&#060;fo rm action="none" method="get"&#062;<BR> &#060;input type="button" name="Calculate Value" value="Calculate" onClick="Calculate()"&#062;<BR>&#060;/form&#062;<BR><BR>&#060;/body&#062;<BR>&#060;/html&#062;<BR>

2. Senior Member
Join Date
Dec 1969
Posts
5,955

## Three things to say to this. Firstly...

...don&#039;t use eval. You will very rarely need eval. Instead just assign the values. Secondly, always finish you JavaScript statement with a semicolon:<BR><BR>var a = 42.52;<BR>var b = 40;<BR>var c = a - b;<BR><BR>Thirdly, floating point numbers, like you are using (42.52), can cause problems with rounding. I have had this problem many times in the past. If you know you are dealing with only two decimal points (for example to add sums of money), then I would work in pennies or cents or whatever the lowest value in your currency is, and then convert it when I display it:<BR><BR>var a = 4252;<BR>var b = 4000;<BR>var c = a - b;<BR><BR>alert(c / 100);<BR><BR>Oliver.

3. Senior Member
Join Date
Dec 1969
Posts
96,118