首页 > 解决方案 > 如果是整数,则追加 ,00

问题描述

我需要附加一个小数,但带有一个昏迷,所以如果是300它应该更改为300,00我有下面的代码并且它可以工作,但如果数字已经是一个小数,它会将它更改为NAN。我需要代码不要修改已经是小数的数字

    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>

标签: javascriptjqueryhtml

解决方案


您可以简单地再添加一个来替换 ( , )replace之后的尾随文本

例子:

        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>


推荐阅读