467,084 Members | 1,219 Online

# Javascript Floating Point Precision Problem

 Hello everyone! I'm new here but have been programming for the web in various languages for 15 years or so. I'm certainly no "expert" but can keep myself out of trouble (or in it?) most of the time. This particular problem has plagued me for years; it is making me very, very, old. :-( It deals with the way Javascript's method of floating point precision takes the simplest math calculations and steals a penny - in the example below, a simple 636.35 is turned into 636.34 (636.34999999999999 !) I know the truncate function below is not only lame, it turns the number into a string - but that is not the issue, as you can see the problem exists before truncate gets to it, and persists even if it is taken out of the script. I won't bore you will all the various methods I've tried, the most obvious being multiply everything by 100 then divide by 100 at the end - all failed PLEASE can someone paste and test this code, offer a solution? Just load it, hit calculate, watch the alerts. I'm turning gray by the minute. :-( THANK YOU! -- Bill Expand|Select|Wrap|Line Numbers          Javascript Floating Point Precision Problem

Javascript Floating Point Precision Problem

\$  \$  \$
\$  \$  \$
\$  \$  \$
TOTAL: \$

function calcForm (form) {                      var subtotal=quan=price=ship=total=0;                    var sub,cancelled;                    var tot       = document.getElementById('po_total');                    var num_items = document.getElementById('number_of_items').value;                      for (i=1;i<=num_items;i++) {                       subtotal = 0;                         sub   = document.getElementById('subtotal_' + i);                       ship  = document.getElementById('shipping_' + i);                       q     = document.getElementById('quantity_' + i);                       p     = document.getElementById('price_' + i);                       subtotal = (q.value * p.value) + (ship.value * 1);                       total += subtotal;                       alert(subtotal + ' ' + total);                       sub.value = truncate(subtotal);                      }                    tot.value = truncate(total);             }               function checkForm (form) {                  calcForm(form);                  alert('various checks, then submit form.');             }               function truncate(num) {                  string = "" + num;                  if (string.indexOf('.') == -1)                  return string + '.00';                  seperation = string.length - string.indexOf('.');                  if (seperation > 3)                  return string.substring(0,string.length-seperation+3);                  else if (seperation == 2)                  return string + '0';                  return string;             }                Aug 1 '06 #1
• viewed: 12707
Share:
5 Replies
 Expert 1GB This might make you mad my very simple solution if this isn't what your looking for let me know and i will give you another solution! num.toFixed(2) :) Expand|Select|Wrap|Line Numbers          Javascript Floating Point Precision Problem

Javascript Floating Point Precision Problem

\$  \$  \$
\$  \$  \$
\$  \$  \$
TOTAL: \$

function calcForm (form) {                      var subtotal=quan=price=ship=total=0;                    var sub,cancelled;                    var tot       = document.getElementById('po_total');                    var num_items = document.getElementById('number_of_items').value;                      for (i=1;i<=num_items;i++) {                       subtotal = 0;                         sub   = document.getElementById('subtotal_' + i);                       ship  = document.getElementById('shipping_' + i);                       q     = document.getElementById('quantity_' + i);                       p     = document.getElementById('price_' + i);                       subtotal = (q.value * p.value) + (ship.value * 1);                       total += subtotal;                       alert(subtotal + ' ' + total);                       sub.value = truncate(subtotal);                      }                    tot.value = truncate(total);             }               function checkForm (form) {                  calcForm(form);                  alert('various checks, then submit form.');             }               function truncate(num) {                  string = num.toFixed(2);                  return string;             }                Aug 1 '06 #2
 Clint, if anything on the Internet makes one mad, it's time to back away from the computer! :-) Thanks for your reply! Funny you should mention toFixed() - I had discovered it through other means (today.) But the problem with the numbers exists long before it gets to truncate() - in fact, by using toFixed() I was able to eliminate that stupid function altogether. Hereis my revised Javascript in its entirety, notice that in the alerts it still displays 636.349999999999 but that toFixed() properly rounds it up to .35. WOO HOO! Many thanks for looking, i have been fighting this Javascript "feature" off and on for years . . . . . Expand|Select|Wrap|Line Numbers                       function calcForm (form) {                      var subtotal,q,p,ship;                    var total = 0;                      var sub,cancelled;                    var tot       = document.getElementById('po_total');                    var num_items = document.getElementById('number_of_items').value;                      for (i=1;i<=num_items;i++) {                       subtotal = 0;                       sub = document.getElementById('subtotal_' + i);                       ship = document.getElementById('shipping_' + i).value;                       q = document.getElementById('quantity_' + i).value;                       p = document.getElementById('price_' + i).value;                         subtotal = (q * p) + (ship * 1);                       total += (subtotal);                       alert(subtotal + ' ' + total);                       sub.value = subtotal.toFixed(2);                       }                    total = total.toFixed(2);                    tot.value = total;             }               function checkForm (form) {                  calcForm(form);                  alert('various checks, then submit form.');             }              Aug 2 '06 #3
 Expert 1GB Yeah i didn't think about what you really said i just got the proper number to display but yes for your answer .toFixed(2) is probably the best way to fix your problem -- i didn't really worry about the alert... all you gotta do is look what i did and change the variable that the alert is coming from and do the toFixed(2) but glad you got it working if you have any more question give us a post. Aug 2 '06 #4
 Expert Mod 8TB This isn't actually a Javascript feature but a feature of the way the IEEE define how floating point numbers are stored in memory. Any language using this definaition suffers from this "feature", for instance C does as well and since javascript is often implemented in C so does Javascript. The problem is that Javascript is using 32 bits of data which have 4294967296 different combinations to hold any value in the range 1.7976931348623158e+308 to 2.2250738585072014e–308 It does this by using a smaller presision value and using some of the bits as a exponent (this can also be done in 16 bits with a smaller range and less presision) which results in it being able to approximate any value in the range but not exactly represent them all (because in real number terms the are an infinaite number of values between any 2 given values). As part of your calculcation clearly the internal representation of the value is going outside the available presision (15 digits for a 32 bit number but only 6 digits for a 16 digit number so perhaps Javascript uses 16 bit floating point values) and you are ending up with an approximation to the value instead of an exact value. We all have to code round this. Sometimes it is easier (particularly with money) when you don't really need the huge range of a floating point value to write your code so that internally it deals with cents (or pence) and only converts to dollars (pounds) for display to the user. This results in all your calculations being performed in integer arithmatic which does not have the imprecisions of floating point arrithmatic. Of course this wont work if you are anticipating many orders greater than \$42,949,672.9 :D Aug 2 '06 #5
 Expert 1GB LOL thanks for the explanation Banfa, i wasn't completely clear on toFixed but now I am. I just knew of several times i have used it to fix the same problem so thats what i gave him. Aug 2 '06 #6