javascriptjquerytofixed

javascript/jquery: how to limit input value to 2 decimals after the point


I am struggling with an input which should give me the substraction from input B - input A in 2 decimals after the point. It works only sometimes:

$('.b').on('keyup', function() {
  var substr = $('.b').val() - $('.a').val();
  $('.c').val(substr).toFixed(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
A <input type="text" class="form-control a" value="" /><br /><br /> B <input type="text" class="form-control b" value="" /><br /><br /> B-A <input type="text" class="form-control c" value="" />

Per example: if you fill in in A: 0.58 and in B 0.82 the value in C is in 2 decimals But if i change the value in B to 0.81, the value of C is NOT in 2 decimals anymore!

Why this strange behaviour?


Solution

  • You should be calling toFixed() on substr:

    $('.b').on('keyup', function() {
        var substr = $('.b').val() - $('.a').val();
        $('.c').val(substr.toFixed(2))
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    A <input type="text" class="form-control a" value="" /><br /><br />
    
    
     B <input type="text" class="form-control b" value="" /><br /><br />
    
    
      B-A <input type="text" class="form-control c" value="" />