javascript
Brief description  about Online courses   join in Online courses
View Rajesh Chandra Benjwal 's Profile

Accuracy in float subtraction

Greeting,

Would you let me know the method to get rid of slight inaccuracy of javascript during subtraction of float values.

Like my calculator code. Whenever I subtract 1 from 1.2 answer would never be .2, I know it is like this in programming languages, but 0.9999999---. So, what change I can do in my clac code to get accurate value.

<form name="calculator" id="calculator">

<input type="text" id= "result" name="result" size="16"><span class="logo">CALC</span>
<br/>

<input type="button" id= "calcbut" name="one" value="1" OnClick="calculator.result.value = '1'" />
<input type="button" id= "calcbut" name="two" value="2" OnCLick="calculator.result.value = '2'" />
<input type="button" id= "calcbut" name="three" value="3" OnClick="calculator.result.value = '3'" />
<input type="button" id= "calcbut" name="plus" value=" " OnClick="calculator.result.value = ' '" />
<br/>
<input type="button" id= "calcbut" name="four" value="4" OnClick="calculator.result.value = '4'" />
<input type="button" id= "calcbut" name="five" value="5" OnCLick="calculator.result.value = '5'" />
<input type="button" id= "calcbut" name="six" value="6" OnClick="calculator.result.value = '6'" />
<input type="button" id= "calcbut" name="minus" value="-" OnClick="calculator.result.value = '-'" />
<br/>

<input type="button" id= "calcbut" name="seven" value="7" OnClick="calculator.result.value = '7'" />
<input type="button" id= "calcbut" name="eight" value="8" OnCLick="calculator.result.value = '8'" />
<input type="button" id= "calcbut" name="nine" value="9" OnClick="calculator.result.value = '9'" />
<input type="button" id= "calcbut" name="times" value="x" OnClick="calculator.result.value = '*'" />
<br/>
<input type="button" id= "calcbut" name="clear" value="c" OnClick="calculator.result.value = ''" />
<input type="button" id= "calcbut" name="zero" value="0" OnClick="calculator.result.value = '0'" />
<input type="button" id= "calcbut" name="zero" value="00" OnClick="calculator.result.value = '00'" />
<input type="button" id= "calcbut" name="div" value="/" OnClick="calculator.result.value = '/'" />
<br />
<input type="button" id= "dobut" name="do" value="=" OnClick="calculator.result.value = eval(calculator.result.value)" />
<input type="button" id= "calcbut" name="backspace" value="Bck" onClick=backs() />
<input type="button" id= "calcbut" name="dot" value="." OnClick="calculator.result.value = '.'" />
<input type="button" id= "calcbut" name="percent" value="%" OnClick="calculator.result.value = '/100'" />

<br/>
</form>

Asked by Rajesh Chandra Benjwal | Mar 26, 2011 |  Reply now
Replies (1)
View teacher siliconindia 's Profile
hi,
use this
c=new Number(a-b+'').toFixed(parseInt(2));
or take help from
http://www.mediacollege.com/internet/javascript/number/round.html
Apr 12, 2011