如何在Javascript中更改小数格式

时间:2017-11-20 10:05:55

标签: javascript formatting

我有以下代码:

function roundNumber(number,decimals) {
  var newString;
  decimals = Number(decimals);
  if (decimals < 1) {
    newString = (Math.round(number)).toString();
  } else {
    var numString = number.toString();
    if (numString.lastIndexOf(".") == -1) {
      numString += ".";
    }
    var cutoff = numString.lastIndexOf(".") + decimals;
    var d1 = Number(numString.substring(cutoff,cutoff+1));
    var d2 = Number(numString.substring(cutoff+1,cutoff+2));
    if (d2 >= 5) {
      if (d1 == 9 && cutoff > 0) {
        while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
          if (d1 != ".") {
            cutoff -= 1;
            d1 = Number(numString.substring(cutoff,cutoff+1));
          } else {
            cutoff -= 1;
          }
        }
      }
      d1 += 1;
    } 
    if (d1 == 10) {
      numString = numString.substring(0, numString.lastIndexOf("."));
      var roundedNum = Number(numString) + 1;
      newString = roundedNum.toString() + '.';
    } else {
      newString = numString.substring(0,cutoff) + d1.toString();
    }
  }
  if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
    newString += ".";
  }
  var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
  for(var i=0;i<decimals-decs;i++) newString += "0";
  //var newNumber = Number(newString);// make it a number if you like
  return newString; // Output the result to the form field (change for your purposes)
}

上面的代码具有十进制输出格式Rp。 3000000.00如果用户在表单上输入价格,我想将小数格式更改为Rp。 3.000.000,00

任何人都可以帮助我?

1 个答案:

答案 0 :(得分:0)

以下代码将为您提供必要的结果:

(3000000.00).toLocaleString('de-DE', {minimumFractionDigits: 2, maximumFractionDigits: 2})

toLocaleString documentation