JavaScript;如何在三位数后设置点?

6pp0gazn  于 5个月前  发布在  Java
关注(0)|答案(6)|浏览(41)

我有以下JavaScript代码:

var calculation = $('select[name=somevalue1] option:selected').data('calc')-($('select[name=somevalue1] option:selected').data('calc')/100*$('select[name=somevalue2] option:selected').data('calc'))-($('select[name=somevalue1] option:selected').data('calc')-($('select[name=somevalue1] option:selected').data('calc')/100*$('select[name=somevalue2] option:selected').data('calc')))/100*$('select[name=somevalue3] option:selected').data('calc');

$('#calculation').text((calculation).toFixed(2).replace(".",","))

字符串
这将计算一个数字,将.改为,,并将其四舍五入到逗号后的两位数。
我需要做的是在树的数字后面加一个点。
平均值:
1.234,56而不是1234,56
1.234.567,89而不是1234567,89
有人知道怎么做吗?

a7qyws3x

a7qyws3x1#

ECMAScript国际化API具有数字格式化功能。Intl.NumberFormat()
你可以这样使用纯JavaScript:

var calculation = document.getElementById('money').value;

//1st way
var moneyFormatter  = new Intl.NumberFormat();
document.getElementById('formattedMoney').innerText = moneyFormatter.format(calculation);

// 2nd way, using currency
var moneyFormatter2 = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2
});

document.getElementById('formattedMoney2').innerText = moneyFormatter2.format(calculation);

个字符
IE11、Firefox和Chrome都支持,但我不确定其他浏览器是否支持。
http://www.ecma-international.org/ecma-402/1.0/#sec-11.1.2
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

zfycwa2u

zfycwa2u2#

您应该使用一个附加的String#replace,并带有一个正则表达式(匹配,之前的三个数字)和一个替换函数(在每个匹配之前添加.)。

您的更新代码:

var calculation = $('select[name=somevalue1] option:selected').data('calc') - ($('select[name=somevalue1] option:selected').data('calc') / 100 * $('select[name=somevalue2] option:selected').data('calc')) - ($('select[name=somevalue1] option:selected').data('calc') - ($('select[name=somevalue1] option:selected').data('calc') / 100 * $('select[name=somevalue2] option:selected').data('calc'))) / 100 * $('select[name=somevalue3] option:selected').data('calc')

function format(n) {
  return n.toFixed(2).replace('.', ',').replace(/\d{3}(?=(\d{3})*,)/g, function(s) {
    return '.' + s
  })
}

$('#calculation').text(format(calculation))

字符串

Demo实现:

var calculations = [
  1234.56,
  1234567.89,
  1234,
  .12
]

function format (n) {
  return n.toFixed(2).replace('.', ',').replace(/\d{3}(?=(\d{3})*,)/g, function (s) {
    return '.' + s
  })
}

console.log(calculations.map(format))

qltillow

qltillow3#

在现代浏览器(Chrome 24+,Firefox 29+,IE 11)上,您可以使用Number.prototype.toLocaleString()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

var number = 3500.12;
console.log(number.toLocaleString());

字符串
这将使用浏览器的区域设置自动格式化数字。我的浏览器设置为德语,因此输出为

3.500,12


如果有不同地区的人使用你的网站,他们会看到他们所期望的数字。

mzsu5hc0

mzsu5hc04#

此功能将为您工作:

function formatNumber(num) {
  var first = num.split(',');
  var digits = first[0].split('').reverse();
  var new_digits = [];
  for(var i =0; i<digits.length; i++) {
    if((i+1)%3==0) {
      new_digits.push(digits[i]);
      new_digits.push('.');
    }
    else {
      new_digits.push(digits[i]);
    }
  }
  var new_num = new_digits.reverse().join("")+','+first[1];
  return new_num;
}

字符串

xam8gpfp

xam8gpfp5#

我从谷歌来到这里只是为了3位数格式的一部分,所以这里的香草代码只是:

格式为3位-基本功能

function formatThreeDigits( integerStr ){
  var len = integerStr.length;
  var formatted = "";
  
  var breakpoint = (len-1) % 3; // after which index to place the dot
  
  for(i = 0; i < len; i++){
    formatted += integerStr.charAt(i);
    if(i % 3 === breakpoint){
      if(i < len-1) // don't add dot for last digit
        formatted += ".";
    }
  }

  return formatted;
}

个字符

格式化为3位-高级功能

function formatThreeDigits(num, decimalDelimiter, digitSeparator){
  // default secondary arguments
  if(arguments.length < 3) digitSeparator = "."; // 3.000.000
  if(arguments.length < 2) decimalDelimiter = ","; // 3,14
  
  let numParts = []; // [0] => integer, [1] => possible decimal part
  let negative = false; // negative or not (e.g. -1)
  
  if( num.substring ){
    // if passed "num" is a STRING:
    numParts = num.split( decimalDelimiter );
  } else {
    // if passed "num" is a NUMBER
    if( num < 0 ){
      negative = true;
      num = num * -1; // turn positive
    }
    
    const numString = num.toString();
    
    // check if it's a decimal number (e.g. 3.14), as it would already have a '.' in it then
    numParts = numString.split(".");
  }
  
  let integer = numParts[0];
  
  const len = integer.length;
  if( len <= 3 ) return (negative ? "-" + num : num); // remember minus if negative!
  
  const breakpoint = ( len - 1 ) % 3; // after which index to place the dot
  
  let formattedNumString = "";
  formattedNumString = negative ? "-" : ""; // prefix "-" is negative
  const loopEnd = len - 3;
  
  for(var i = 0; i < loopEnd; i++){
    formattedNumString += integer.charAt(i);
    if(i % 3 === breakpoint){
      formattedNumString += digitSeparator;
    }
  }
  formattedNumString += integer.substr(-3, 3);
  formattedNumString += numParts[1] ? decimalDelimiter + numParts[1] : "";
  
  return formattedNumString;
}


这是相同的代码,但所有的铃铛和哨子,选项,边缘情况覆盖,略有优化,并考虑到十进制数字。

dkqlctbz

dkqlctbz6#

这段代码为我工作:

<p id="calculation"></p>

<script>
    function numberWithCommas(x) {
        var parts = x.toString().split(".");
        parts[0]=parts[0].replace(/\B(?=(\d{3})+(?!\d))/g,".");
        return parts.join(",");
        }

        var calculation = 1231739216.34367;

        document.getElementById("calculation").innerHTML = numberWithCommas((calculation).toFixed(2))
</script>

字符串
此代码将:
1.四舍五入(用于商业)到两位数后的数字。
1.将小数点改为逗号。
1.在小数点前每隔三位设置一个点。

相关问题