首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Numeral.js在%中舍入JSON数字

使用Numeral.js在%中舍入JSON数字
EN

Stack Overflow用户
提问于 2022-05-30 13:33:29
回答 1查看 46关注 0票数 0

我从API中获取json数据,我必须将其中一些数字显示为%。json数据显示它们为0.00。我试过这个方法,但没成功。我想使用一个url来获取我的数据,然后使用Numeral.js来生成我在%中获得的过滤数据。我做错了什么?我为我的图形创建了一个模板。然后,我发出一个提取请求来获取数据并对其进行过滤,因此我得到了所需的值。然后,我取这个值,并尝试格式化它。我想把新的值放在图表上。

代码语言:javascript
复制
const data = {
  labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  datasets: [
    {
      label: "ADOPTION",
      data: [18, 12, 6, 9, 12, 3, 9],
      backgroundColor: "rgba(73, 117, 197, 1)",
      borderColor: "rgba(73, 117, 197, 1)"
    },
    {
      label: "Target",
      data: [0.654, 0.654, 0.751],
      backgroundColor: "rgba(236, 123, 46, 1)",
      borderColor: "rgba(236, 123, 46, 1)"
    }
  ]
};
// config for graph
const config = {
  type: "line",
  data: data,
  options: {
    plugins: {
      title: {
        display: true,
        text: 'data'
      },
    },
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
};

// render init block
const myChart = new Chart(
  document.getElementById("data"),
  config
);

// Fethc block  for the   graph
async function fetchJSON() {
  const url="link";
  const response = await fetch(url);
  //* loads waiting to complete the request
  const datapoints = await response.json();
  return datapoints;
}

fetchJSON().then((datapoints) => {
  const month = datapoints.map(function (index) {
    return index.PERIOD_NAME; //*reffers to jSon word from file
  });
  console.log(month);
  myChart.config.data.labels = month;
  myChart.update();
});

fetchJSON().then((datapoints) => {
  const total = datapoints.map(function (index) {
    return index.ADOPTION //*reffers to jSon word from file
  });
  var string = numeral(datapoints).format('0.000%');
  console.log(string);
  myChart.config.data.datasets[0].data = total;
  myChart.update();
});
代码语言:javascript
复制
<div class="col-sm-12 col-md-4 col-lg-4">
            <canvas id="data"></canvas>
 </div>
 
 <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-30 14:19:14

我猜datapoints是一个数组。数字接受它尝试转换成数字的数字或字符串。您可以使用datapoints.map(val => numeral(val).format('0.00%'))来格式化数据点元素。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72435213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档