Rzj Hayabusa
Rzj Hayabusa

Reputation: 657

How to set operators output in jQuery into thousands separators and 2 decimals points?

I have these html input to calculate two input 1 & 2 and display the result into the input 3:

<input type="text" class="inputdecimals" id="txt_balance_dec" name="txt_balance_dec" value="0.00">
<input type="text" class="inputdecimals" id="txt_nett_dec"    name="txt_nett_dec"    value="0.00"readonly>


<input type="text" class="inputdecimals" id="txt_balance_nov" name="txt_balance_nov" value="0.00">

Here's the jQuery for the inputdecimals :

<script>
    $(document).ready(function(e){
        $('input.inputdecimals').keyup(function(event) {
            if(event.which >= 37 && event.which <= 40) return;
            $(this).val(function(index, value) {
              return value
              .replace(/[^\d.]/g, "")
              .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
              .replace(/\.(\d{2})\d+/, '.$1')
              .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
              ;
            });
          });
    });
</script>

My goal is to subtract the value (txt_bal_dec - txt_bal_nov) and display the total into txt_nett_dec.

Since my input HTML input already change the value into thousand separators and 2 decimals point, output did not show as I want.

for example 10,000.00 - 6,000.00 is equal to 6, not 6,000.00 (Picture below)

enter image description here

I'm not sure how to replace the thousand separator first and then calculate while keep maintain the 2 decimals. when show the output i need to put back the thousand separator and 2 decimals.

My jQuery calculation as below. Sorry, I'm not really good in jQuery.

$("#txt_balance_dec").keyup(function() {
        var bal_dec = parseFloat($(this).val(), 2);
        var bal_nov = parseFloat($('#txt_balance_nov').val(), 2);
        var result = bal_dec - bal_nov;
        $('#txt_nett_dec').val(result);
    }); 

Appreciate if someone can help me to fix this problem. thanks.

Upvotes: 0

Views: 361

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

You have to strip all commas out of the string before you attempt to parse it, as parsing a number with commas will only parse up to the first comma.

//For example           Result
parseFloat("5,4,3")     // 5
parseFloat("15,000")    // 15
parseFloat("123,456")   // 123

This can be done using a simple replace: .replace(/,/g,'');


I've also made a few changes just to tidy up:

  • Made a function that does both replace and parseFloat called parseCurrency, to make it easily reusable
  • Put your formatting into a function called formatCurrency, to make it easily reusable
  • Made dec_balance and nov_balance inputs can share an event, since a change to either should force a net recalculation

const formatCurrency = (str) => (""+str).replace(/[^\d.]/g, "").replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3').replace(/\.(\d{2})\d+/, '.$1').replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const parseCurrency = (str) => str.replace(/,/g,'');

$('input.inputdecimals').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val((i,v) => formatCurrency(v));
});

$("#txt_balance_dec, #txt_balance_nov").keyup(function() {
  var bal_dec = parseCurrency( $("#txt_balance_dec").val() );
  var bal_nov = parseCurrency( $("#txt_balance_nov").val() );
  var result = bal_dec - bal_nov;
  $('#txt_nett_dec').val(formatCurrency(result));
});
input { display: block; margin: 10px 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Dec <input type="text" class="inputdecimals" id="txt_balance_dec" name="txt_balance_dec" value="0.00">
Nov <input type="text" class="inputdecimals" id="txt_balance_nov" name="txt_balance_nov" value="0.00">
Net <input type="text" class="inputdecimals" id="txt_nett_dec" name="txt_nett_dec" value="0.00" readonly>

(It's also worth noting that your formatting function seems to strip -, therefore the net will be an absolute value.)

Upvotes: 2

Related Questions