Click to See Complete Forum and Search --> : Floating point numbers


MattOz
05-09-2003, 06:19 AM
Hi there,

There must be an easy answer to this question....

I am using the parseFloat function to add a series of 'numerical' entries entered on a form and am displaying the running total in another cell. I want to display this running total correct to two decimal places at all times, but I don't seem to be able to find a simple way of doing this.

eg. 1+10.10 displays at 10.1. 10.33+10.66 displays as 20.990000000000002.

Does anyone have any suggestions?

Thanks,
Matt

Charles
05-09-2003, 06:36 AM
<script type="text/javascript">
<!--
alert (Math.PI.toFixed(4));
// -->
</script>

However, Number.toFixed() wasn't introduced until JavaScript 1.3 I believe. If you are worried about older browser then use:

<script type="text/javascript">
<!--
if (!Number.prototype.toFixed) {Number.prototype.toFixed = function (places) {
if (places > 20 || places < 0) return;
places = Math.round (places);
var n = (Math.round(Math.abs(this) * Math.pow(10, places))).toString();
for (var i=1; i<=places; i++) {if (n < Math.pow(10,i)) n = '0' + n};
if (this < 0) n = '-' + n;
return n.slice(0, -(places)) + '.' + n.slice(-(places));
}}
alert (Math.PI.toFixed(4));
// -->
</script>

But then this is JavaScript. It won't work one in ten times anyway.

MattOz
05-09-2003, 07:22 AM
Thanks for your help Charles.