skip to Main Content

    <script type="text/javascript">
   $(document).ready(function() { 
  
  $('#btn-add').click(function(){
      $('#select-from option:selected').each( function() {
              $('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
          $("input[name='class']").val(parseFloat($(this).val()) + parseFloat($("input[name='class']").val()));
      });
  });
  $('#btn-remove').click(function(){
      $('#select-to option:selected').each( function() {
          $('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
          $(this).remove();
          $("input[name='class']").val(parseInt($("input[name='class']").val() - parseInt($(this).val())));
          total= $("input[name='class']").val(parseInt($("input[name='class']").val() - parseInt($(this).val())));
      });
  
  });
    
   });
    </script>

I would like to shorten the number after decimal numbers to 2. Does somebody has any idea

2

Answers


  1. You can use the toFixed method.

    Your code should be:

        <script type="text/javascript">
       $(document).ready(function() { 
      
          $('#btn-add').click(function(){
              $('#select-from option:selected').each( function() {
                  $('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
                  $("input[name='class']").val((parseFloat($(this).val()) + parseFloat($("input[name='class']").val())).toFixed(2));
              });
          });
    
          $('#btn-remove').click(function(){
              $('#select-to option:selected').each( function() {
                  $('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
                  $(this).remove();
                  var newValue = parseInt($("input[name='class']").val() - parseInt($(this).val()));
                  $("input[name='class']").val(newValue.toFixed(2));
              });
          });
        
       });
    </script>
    

    Example output: 2.01

    Login or Signup to reply.
  2. var num = 1.345
    console.log(num.toLocaleString('en-UK', { maximumFractionDigits: 2, minimumFractionDigits: 2 }))
    console.log(num.toLocaleString('it-IT', { maximumFractionDigits: 2, minimumFractionDigits: 2 }))

    I prefer this format to use different countries. Try it and tell me.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search