使用 Numeral.js 以 % 舍入 JSON 数字

Using Numeral.js to round JSON numbers in %

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

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();
});
<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>

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