Problem with JavaScript arithmetic

Posted by Lynn on Stack Overflow See other posts from Stack Overflow or by Lynn
Published on 2010-06-02T22:13:22Z Indexed on 2010/06/02 22:34 UTC
Read the original article Hit count: 324

Filed under:

I have a form for my customers to add budget projections. A prominent user wants to be able to show dollar values in either dollars, Kila-dollars or Mega-dollars.

I'm trying to achieve this with a group of radio buttons that call the following JavaScript function, but am having problems with rounding that make the results look pretty crummy.

Any advice would be much appreciated!

Lynn

function setDollars(new_mode)
 {
  var factor;
  var myfield;
  var myval;

  var cur_mode = document.proj_form.cur_dollars.value;

  if(cur_mode == new_mode)
   {
    return;
   }
  else if((cur_mode == 'd')&&(new_mode == 'kd'))
   {
     factor = "0.001";
   }
  else if((cur_mode == 'd')&&(new_mode == 'md'))
   {
     factor = "0.000001";
   }
  else if((cur_mode == 'kd')&&(new_mode == 'd'))
   {
     factor = "1000";
   }
  else if((cur_mode == 'kd')&&(new_mode == 'md'))
   {
     factor = "0.001";
   }
  else if((cur_mode == 'md')&&(new_mode == 'kd'))
   {
     factor = "1000";
   }
  else if((cur_mode == 'md')&&(new_mode == 'd'))
   {
     factor = "1000000";
   }

  document.proj_form.cur_dollars.value = new_mode;

  var cur_idx = document.proj_form.cur_idx.value;
  var available_slots = 13 - cur_idx;
  var td_name;
  var cell;
  var new_value;

  //Adjust dollar values for projections
  for(i=1;i<13;i++)
   {
    var myfield =  eval('document.proj_form.proj_'+i);
    if(myfield.value == '')
     {
      myfield.value = 0;
     }
    var myval = parseFloat(myfield.value) * parseFloat(factor);
    myfield.value = myval;
    if(i < cur_idx)
     {
      document.getElementById("actual_"+i).innerHTML = myval;
   }
 }

© Stack Overflow or respective owner

Related posts about JavaScript