首页 > 解决方案 > 如何在 JS 数字中添加千位分隔符以进行字符串输出?

问题描述

我有一个 API 调用正在进行,它将venue_capacity足球队的返回作为没有千位分隔符的数字。我想将其打印为字符串并包含千位分隔符。

我的想法是在我从 API 获得数据后运行该函数以相应地操作变量venue_capacity

这是我目前的尝试(来自这个线程:如何在 JavaScript 中用逗号打印一个数字作为千位分隔符),它返回没有分隔符的数字:

  $.ajax({
    method: "GET",
    async: "True",
    dataType: "json",
    url: "https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/teams/team/" + team_id,
    success: function(response) {
      var team_info = response;
      console.log(team_info);

      team = team_info.api.teams[0].name;
      founded = team_info.api.teams[0].founded;
      venue_capacity = team_info.api.teams[0].venue_capacity;

      function numberWithCommas(venue_capacity) {
        return venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
      }

      $("#selectedClub").html(team);
      $("#founded").html(founded);
      $("#venue_capacity").html(venue_capacity);

    }

标签: javascriptjquery

解决方案


您不必function在范围内声明 s $.ajax- 只需一次性执行翻译:

venue_capacity = team_info.api.teams[0].venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");

推荐阅读