JS formatnumber/addcommas 不工作

JS formatnumber/addcommas not working

我使用的是 wordpress,我有一些插件可以用来尝试帮助提高一些页面速度得分。话虽这么说,我已经在网站上做了一些定制,当我这样做时,我失去了 addcommas 功能,它似乎是我在栏上的范围滑块。我不能再用数字显示逗号了。它只是显示美元符号。我试过禁用插件,但似乎没有什么不同。

站点是www.cjhitch.com

这是滑块

<div>

<div id="slider" class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">

<i class="bulleft"></i>
<i class="bulright"></i>
<div id="slider-min">

    0,000

</div>
<div id="slider-max">

    ,000,000

</div>
<div class="ui-slider-range ui-widget-header ui-corner-all ui-slider-range-min"></div>
<span class="ui-slider-handle ui-state-default ui-corner-all div-cover" tabindex="0">

   <input id="amount" type="text" readonly=""></input>
</span>

</div>
</div>

等号不是代码的一部分,我不得不用它来让它们显示出来。

这是JS

<script>
 $(function() {
 $( "#slider" ).slider({
  range: 'min',
  value: 250000,
  min: 100000,
  max: 2000000,
  step: 1000,
  slide: function( event, ui ) {
   $("#amount").val("$" + addCommas(ui.value));
    $("#result1").val("$" + formatNumber(Math.round(ui.value*.033 - 2799)));
    $("#result2").val("$" + formatNumber(Math.round(ui.value*.06 -5299)));
    $("#result3").val("$" + formatNumber(Math.round(ui.value*.06 -3799)));
  }
 });

function formatNumber (num) {
  return num.toString().replace(/(d)(?=(d{3})+(?!d))/g, ",")
}

console.info(formatNumber(2665));      // 2,665
console.info(formatNumber(102665));    // 102,665
console.info(formatNumber(111102665)); // 111,102,665

$('#amount').val( "$" +          formatNumber($("#slider").slider("value"))).detach().appendTo('.ui-slider-handle');
$('.ui-slider-handle').prepend('<i class="fa fa-usd"></i>');

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(d+)(d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '' + ',' + '');
}
  return x1 + x2;
}
});
</script>

如您所见,我尝试了两种不同的方式,数字格式和添加逗号。过去它们都同时起作用,但现在似乎是"sanitizing"它。

如果有人知道如何解决这个问题,我将不胜感激!

Intl.NumberFormat() 与您尝试执行的任务完全相同。所以你最好使用它,因为它做了它应该非常方便的事情。这里唯一的缺点是 Safari 不支持它作为唯一的浏览器,但你可以使用这个包:

https://github.com/andyearnshaw/Intl.js

填充。

这是我在上面链接的有关用法的 mozilla 文档的副本:

var number = 123456.789;

// request a currency format
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// → 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// → ¥123,457

// limit to three significant digits

    console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// → 1,23,000

在我看来,这是因为 ui.value 不包含点 (.) 而您没有拆分它。 试试这个。

function addCommas(nStr){
    nStr += '';
    x = nStr.split( /(?=(?:...)*$)/);
    return x;
}

当然你可以在结果上使用这个函数,例如:

$("#result1").val("$" + addCommas(formatNumber(Math.round(ui.value*.033 - 2799))));