0

I have a bit of javascript that dynamically multiplies what users are typing in a text field (by the base var), and displays it in a span. Now I'm just trying to figure out how to get the decimal places of the result to float to 2 places, i.e. 10.00 instead of 10 I found the toFixed function, but can't seem to use it properly... I'd appreciate any help. Thanks

<input id="quantity">
<span id="result"></span> 
<script>

window.onload = function() {
   var base = 3;
   document.getElementById('quantity').onkeyup = function() {
      if(this.value.length == 0) {
         document.getElementById('result').innerHTML = '';
         return;
      }
      var number = parseInt(this.value);
      if(isNaN(number)) return;
      document.getElementById('result').innerHTML = number * base;
   };
   document.getElementById('quantity').onkeyup();
};
1
  • Are you sure you want to use parseInt here? It will turn '4.21' into '4'. So the user will be told that 4.21 * 3 = 12.00, which it doesn't. parseFloat will yield a floating point value. Commented Mar 13, 2013 at 16:08

1 Answer 1

1
window.onload = function() { 
 var base = 3; 
 document.getElementById('quantity').onkeyup = function() { 
   if(this.value.length == 0) { 
     document.getElementById('result').innerHTML = ''; 
     return; 
   }    
   if(isNaN(this.value)) 
     return; 
   var number = parseFloat(this.value); 
   var result = (number * base).toFixed(2);
   document.getElementById('result').innerHTML = result; 
   }; 
   document.getElementById('quantity').onkeyup();
};
Sign up to request clarification or add additional context in comments.

1 Comment

Firstly, can you change parseInt to parseFloat, since the asker is unlikely to want an integer multiplied to 2dp. Also, it might be clearer to have either var result = (number * base).toFixed(2); (expressing it in one statement), or to have two variables and have var preciseResult = number * base; var result = preciseResult.toFixed(2);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.