Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Javascript subtraction help needed

Posted on 2007-03-31
10
209 Views
Last Modified: 2013-11-23
I can't see to figure this one out... yet it seems so simple

when I calculate the following equation I am getting a very out results  5.21-5 = .2099999999999999998.

I need it to compute the actual value which is .2100000

function ComputeChange5(Start, Change, End) {
         document.MainForm[Change].value = formatNum(eval(5.21-5),"^#,###.5^");
}


I am looking for a very simple solution... I apss into the function the start and end values, and then look for the change value (which is the subtraction). I tried to simplify the code above after I narrowed down that its not my passed in variables, its simply the calucation. thx.
0
Comment
Question by:mrferrari
  • 5
  • 4
10 Comments
 
LVL 36

Accepted Solution

by:
Zyloch earned 500 total points
ID: 18829390
The problem is caused by round off error in the Javascript. You might want to try something like:

var number = 5.21 - 5;
alert(number.toFixed(7));
0
 
LVL 63

Expert Comment

by:Zvonko
ID: 18829391
The fractal number is the nature of digital computer number representation.
That effect is stumping already others, but what do you want to ahieve?
Do you need help for that formatNum() function?
Do you know the method toFixed(2)
Like this:
  alert((5.21-5).toFixed(2));

0
 
LVL 36

Expert Comment

by:Zyloch
ID: 18829392
The toFixed() function will round your number to the number of decimal places that you want. I am not too sure why you need to use eval() either.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

Author Comment

by:mrferrari
ID: 18829398
this is my full function

function ComputeChange5(Start, Change, End) {
      var vartotal = 0;
      var varname = "";
      var FieldName = End;
            
      if (document.MainForm[FieldName].value.replace(/\,/g,"") == ''|| isNaN(document.MainForm[FieldName].value.replace(/\,/g,""))){
                  document.MainForm[FieldName].value = formatNum(eval(document.MainForm.oldvarstorage.value.replace(/\,/g,"")),"^#,###.5^");
                  alert('You entered an invalid number')
                  document.MainForm[FieldName].focus();}
            else
                  {
                  if (document.MainForm[End].value == document.MainForm.oldvarstorage.value)
                        {}
                  else
                        {
                        vartotal = numbertofixed(eval(document.MainForm[End].value.replace(/\,/g,"")),5) - eval(document.MainForm[Start].value.replace(/\,/g,""));
                        document.MainForm[End].value = formatNum(eval(document.MainForm[End].value),"^#,###.5^");
                        document.MainForm[Change].value = formatNum(eval(vartotal),"^#,###.5^");
                        }
            }            
      }
0
 

Author Comment

by:mrferrari
ID: 18829405
thanks...

I just change the last statement formatNum(eval(vartotal),"^#,###.5^");

to vartotal.toFixed(5)

any other suggestion on the function would be helpful, I am very new to java and frankly don;t use it much except these calculation functions... here and there.

thanks, enjoy your day.
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 18829412
There are parts of your function that seem repetitive or useless. For instance, what is the purpose of the FieldName variable?

Also, instead of

    if (document.MainForm[FieldName].value.replace(/\,/g,"") == ''|| isNaN(document.MainForm[FieldName].value.replace(/\,/g,""))){

if may be easier to use

var num = parseFloat(document.MainForm[End].value.replace(/,/g, ''));
if (isNaN(num)) {


Also,

 if (document.MainForm[End].value == document.MainForm.oldvarstorage.value)
                        {}

does not seem necessary. It does not hurt to format the number again if it is the old one.
0
 

Author Comment

by:mrferrari
ID: 18829458
cool. super thanks. look at it now...

note, I have another function which is compute change. It is virtually the same code, but I just changed field name, that is why I left it in there at the top

function ComputeChange5(Start, Change, End) {
      var vartotal = 0;
      var FieldName = End;
      var Num = parseFloat(document.MainForm[FieldName].value.replace(/\,/g,""))
            
      if (isNaN(Num))
                  {
                  document.MainForm[FieldName].value = formatNum(eval(document.MainForm.oldvarstorage.value.replace(/\,/g,"")),"^#,###.5^");
                  alert('You entered an invalid number')
                  document.MainForm[FieldName].focus();}
            else
                  {
                  vartotal = eval(document.MainForm[End].value.replace(/\,/g,"")) - eval(document.MainForm[Start].value.replace(/\,/g,""));
                  document.MainForm[End].value = formatNum(eval(document.MainForm[End].value),"^#,###.5^");
                  document.MainForm[Change].value = vartotal.toFixed(5);
                  }            
      }
0
 

Author Comment

by:mrferrari
ID: 18829469
sad is I also have a function

function ComputeChange2(Start, Change, End)

which just replaces all the 5's with 2's and return 2 deciaml place results...

it was easier for me to copy the code that incorporate the logic into the function and pass in another parameter... looking back it seems lazy to me... im guilty and will fix it.

thanks again for the advice.

Marc
0
 

Author Comment

by:mrferrari
ID: 18829489
should I even be using eval and the format num?

how do I make the formatnum parameter, ,"^#,###.5^" dynamic, so I can pass in either a 2 or 5 to specify how many decimals I want...

I would like to award you some more points....

Marc
0
 
LVL 36

Expert Comment

by:Zyloch
ID: 18829571
It depends on how formatnum is coded. In fact, it may be easier to take out the .5 part of the format number and just use toFixed() explicitly.

If you want, you can always use something such as:

"^#,###." + VariableHoldingDecimalPlaces + "^"

Finally, you do need the majority of your eval() functions. You only need that if you have complex Javascript as a string and need to run it.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

791 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question