javascript - 如果是整数则追加 ,00

标签 javascript jquery html

我需要附加一个小数,但带有逗号,所以如果是 300 它应该更改为 300,00 我有下面的代码并且它可以工作,但是如果number 已经是小数,它会将其更改为 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>

最佳答案

您只需再添加一个额外的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>

关于javascript - 如果是整数则追加 ,00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55979319/

相关文章:

javascript - CSS 动画 : changing images in an infinite loop

javascript - 如何使这段代码更清晰?

javascript - Magnific Popup 的自定义标题

python - 使用 Python 对 HTML 源代码进行标记和标记

javascript - 播放完整的 HTML5 视频,然后循环播放其中的一部分

javascript - Python 获取具有 javascript 的网页内容 - 也许是 Selenium

javascript - 获取 SVG 元素上的 offsetTop

javascript - 将响应列表从水平更改为垂直 CSS

javascript - 如何使用javascript保存背景颜色?

html - html代码中的字体大小