Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

javascript - math leaving off a digit

Posted on 2009-06-30
10
Medium Priority
?
284 Views
Last Modified: 2012-05-07
Hi,

I have a javascript that converts numbers to decimals (adds decimals if needed and does simple math).  It uses three fields to autoFill the 4th.  Field 1 is addition.  Field 2 subtraction.  Field 3 addition.  Field 4 should reflect the calculation of 1,2,3.  The problem is this.  If I type 20 into field 1, field four shows 2.00... and NOT 20.00.  This si probably a simple fix, and this was working great when I was using onChange instead of onKeyPress.  

Code is below.  Thank you very very much ... Wendi~
<script type="text/javascript">
 
function calc(){
  one = document.autoSumForm16.budget_income1.value;
  two = document.autoSumForm16.budget_income2.value;
  three = document.autoSumForm16.budget_income3.value;
      if (one >'' && two > '' && three > '' ) {
      var sum  = parseInt(one) - parseInt(two) + parseInt(three);
      
      var num = new NumberFormat(sum).toFormatted();
      document.autoSumForm16.budget_income4.value = num;
	  document.autoSumForm16.budget_exp4.value = num;
      }
      else  
      {
            alert ('Please enter a number.  No commas or letters.');
            }
}
 
 
function CurrencyFormatted(amount)
{
        var i = parseFloat(amount);
        if(isNaN(i)) { i = 0.00; }
        var minus = '';
        if(i < 0) { minus = '-'; }
        i = Math.abs(i);
        i = parseInt((i + .005) * 100);
        i = i / 100;
        s = new String(i);
        if(s.indexOf('.') < 0) { s += '.00'; }
        if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
        s = minus + s;
        return s;
}
 
 
</script> 
 
<!--- These three fields calc the one below.  I want it to be where simply typing being the calculation, and instantly changes
      the number below --->
<input type="Text"  name="budget_income1" style="text-align:right;" onKeyPress="calc();" value="0">
<input type="Text"  name="budget_income2" style="text-align:right;" onKeyPress="calc();" value="0">
<input type="Text"  name="budget_income3" style="text-align:right;" onKeyPress="calc();" value="0">
 
 
<!--- This is the field being calculated by the 3 above --->
<input type="Text"  name="budget_income4"  style="text-align:right;" value="#getform.budget_income4#">

Open in new window

0
Comment
Question by:wkolasa
[X]
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
  • 7
  • 2
10 Comments
 

Author Comment

by:wkolasa
ID: 24746921
The issue is in the function calc()
0
 

Author Comment

by:wkolasa
ID: 24746969
The issue, which i haven't solved, is this.  Because of the onKeyPress instead of onChange, javascript doesn't know/care about decimals from the first three inputs.  In other words... if in the first field I type 10.00, field 4 = 10.00.  But if in the first field I type 1,   field 4 = 0.00
0
 

Author Comment

by:wkolasa
ID: 24747115
parseInt  is not digging the onKeyPress   but even knowing that I don't have a solution yet
0
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
LVL 41

Expert Comment

by:HonorGod
ID: 24747269
1. You don't want to be calling calc when a key is pressed.  This is a really bad idea...

2. To check for non-empty fields, change your if expression from this:

    if (one >'' && two > '' && three > '' ) {

    to this:

    if (one && two && three ) {

3. When you use parseInt(), be sure to include/specify the radix.  So, instead of using

    var sum  = parseInt(one) - parseInt(two) + parseInt(three);

    Use this instead:

    var sum  = parseInt( one, 10 ) - parseInt( two, 10 ) + parseInt( three, 10 );
0
 

Author Comment

by:wkolasa
ID: 24747277
Excellent.  Thank you.  I Know, beleive me I know this is a bad idea.  The client is demanding it.
0
 

Author Comment

by:wkolasa
ID: 24747312
I set the function as you outlined.  I'm still having the same problem though.  I tried to add decimals using toFixed... no good (probably a dumb idea, but I pretty new with javaScript).
0
 

Author Comment

by:wkolasa
ID: 24747349
The function simply doesn't see the first digit of the onKeyPress event
0
 
LVL 7

Expert Comment

by:Xxavier
ID: 24747418
Looking at this I think you have made a simple problem very complicated. There are a number of easy ways of converting to numbers to  do arithmetic.  I can not test your code as it is incomplete., however

(1) Multiply a string by 1.0 converts it to a number
(2) num.toFixed(2) ouputs num to 2 decimal places
(3) isNaN(num) checks if num is a number

0
 
LVL 7

Accepted Solution

by:
Xxavier earned 2000 total points
ID: 24747553
also you need onKeyUp()  no  onKeyPress()

try this
<script type="text/javascript">
 
function calc(){
  one = 1*document.autoSumForm16.budget_income1.value;
  two = 1*document.autoSumForm16.budget_income2.value;
  three = 1*document.autoSumForm16.budget_income3.value;
      if (isNaN(one)|isNaN(two)|isNaN(three)){ 
             alert ('Please enter a number.  No commas or letters.');
             return
       }
      var num = one - two + three;
      document.autoSumForm16.budget_income4.value = num.toFixed(2);
 }
 
 
 
 
</script> 
 
<form name=autoSumForm16>
<input type="Text"  name="budget_income1" style="text-align:right;" onKeyUp="calc();" value="0">
<input type="Text"  name="budget_income2" style="text-align:right;" onKeyUp="calc();" value="0">
<input type="Text"  name="budget_income3" style="text-align:right;" onKeyUp="calc();" value="0">
 
<!--- This is the field being calculated by the 3 above --->
<input type="Text"  name="budget_income4"  style="text-align:right;" value=""> </form>

Open in new window

0
 

Author Closing Comment

by:wkolasa
ID: 31598397
You're right, it is overly complicated.  Can't be helped.  Much of the code,  convoluted structure is already in place.  

Thank you very much!
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

670 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