如何格式化数字到货币?

时间:2017-03-15 04:44:52

标签: javascript

我目前正在将数字格式化为货币,但不处理数组的集合。我用javascript来使用Math.round函数。我想知道如何正确使用此功能。我很感激你的建议。谢谢。

数组:

{
    "data": [
        [
           "9812355000",
            "23397000",
            "13976000"
        ]
    ]
}

for (var x = 0; x < data.data.length; x++) {
    for (var i0 = 0; i0 < data.data[x].length; i0++) {
        dynamicColumn += `<td>${data.data[x][i0] === null || data.data[x][i0] === "" 
                        ? 0 
                        : Math.round(data.data[x][i0])}</td>`;
   }
}

需要实现:

9,812,355,000
23,397,000
13,976,000

3 个答案:

答案 0 :(得分:0)

point = Cursor.Position;
point.X -= this.Size.Width / 2;
WindowsAPI.SetWindowPos(this.Handle, IntPtr.Zero, point.X, point.Y, 0, 0, SWP_MOVE);

或内联:

var thousandSeparationRegexp = /\B(?=(\d{3})+(?!\d))/g;

// iterate through numbers
var numberString = number.toString();
var formatted = numberString.replace(thousandSeparationRegexp, ',');

答案 1 :(得分:0)

要实现使用数组指定的输出,可以向后迭代数字(意味着从最后一个数字开始并移动到第一个数字),然后在3个数字后插入逗号。一些示例代码可能如下所示:

for(let i = numberString.length - 1; i >= 0; i--) {
   if (i % 3 === 0)
      array.insert(i, ','); // this is not a real function. I leave it up to you to implement this. first param is index and second is what to insert
}

答案 2 :(得分:0)

您可以使用Intl.NumberFormat()。format(x):

&#13;
&#13;
getData = async () => {
  const name = firebase.database().ref('/users/user_uid_0/name');

  var data = await name.once('value')
    .then(snapshot => {
      console.log("value", snapshot.val());
      return snapshot.val();
    })
    .catch(e => {
      console.log("firebase error", e);
      return null;
    });

  return data;
}
&#13;
function myFunction() {
  var x = document.getElementById("value_unformated").value
  var a = Intl.NumberFormat().format(x)
  var text = "Currency format: " + a + "<br>";
  document.getElementById("value_formated").innerHTML = text;
}
&#13;
&#13;
&#13;