Append ,00 if is a whole number

Asked by At

I need to append a decimal but with a coma so if is 300 it should change to 300,00 I have the code below and it works, but if the number already is a decimal it will change it to NAN. I need the code not to modify the numbers that already are decimals

    var formatter = new Intl.NumberFormat('es-ES', {
      style: 'currency',
      currency: 'USD',
    });
    $('.total-amount').each(function() {
      var x = $(this).text().replace(/[^\d,]/g, "");
      $(this).text(formatter.format(x));
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total-in-basket">
  <div class="total-description">
    total is:
  </div>
   <p> with decimal example: </p>
  <div class="total-amount">
    $ 300,00
  </div>
  <p> without decimal example: </p>
  <div class="total-amount">
    $ 300
  </div>
</div>

3 Answers

3
saurabh On Best Solutions

You can simply add one more extra replace to replace the trailing text after ( , )

Example:

        var formatter = new Intl.NumberFormat('es-ES', {
          style: 'currency',
          currency: 'USD',
        });
        $('.total-amount').each(function() {
          var x = $(this).text().replace(/[^\d,]/g,"").replace(/,.*$/g,""); /*<- add this*/ 
          $(this).text(formatter.format(x));
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="total-in-basket">
      <div class="total-description">
        total is:
      </div>
      <p> with decimal example: </p>
      <div class="total-amount">
        $ 300,00
      </div>
      <p> without decimal example: </p>
      <div class="total-amount">
        $ 300
      </div>
    </div>

0
Maheer Ali On

You can use includes() to check if there is already a comma in text.

var formatter = new Intl.NumberFormat('es-ES', {
style: 'currency',
 currency: 'USD',
});
$('.total-amount').each(function() {
  let text = $(this).text();
  if(!text.includes(',')){
    var x = text.replace(/[^\d,]/g, "");
    $(this).text(formatter.format(x));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total-in-basket">
 <div class="total-description">
total is:
  </div>
<div class="total-amount">
$ 12,200
  </div>
</div>

1
sensor On

I would do something like:

const formatCurrency = function (number) {
   const f = new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'USD' });
   if (number != parseInt(number, 10)) {
      return number;
   }
   return f.format(number)
}

and use it the same way:

$('.total-price').each(function() {
    var x = $(this).text().replace(/[^\d,]/g, "");
    $(this).text(formatCurrency(x));
});

That way you will format the number only when it is an integer and return the number unmodified otherwise.