Wednesday, June 01, 2011

Javascript Subtraction without the extra decimals

I needed to do a simple javascript subtraction but forgot about the floating point. This puts a 1 "x" decimal places to the right of the decimal point. This is because computers work in binary rather than numbers.

To get around this I used the JavaScript round() Method and the code can be shown below:

<script language="Javascript" type="text/javascript">
<!--
var value1 = 25.00;
var value2 = 23.98;
var result = (value1 - value2) * 100;
var Myresult = Math.round(result) / 100;
document.write("My result is " + Myresult + " and no weird decimals");
//-->
</script>

No comments: