如何使用 JavaScript 设置弹出窗口的小数位数?

How can I set the number of decimals on a popup using JavaScript?

我在网站上有一个弹出窗口,显示来自 geoJSON 文件的值。现在,它看起来如下图所示:

这是当前代码:

function popUp_cc_210303(f, l) {
  var out = [];
  if (f.properties) {
    var url =
      '<a href=/uas_tools/crop_analysis/index.php?crop=Wheat&year=2021&location=Amarillo&sublocation=Irrigation';
    var parameters = '';
    for (key in f.properties) {
      out.push(key + ': ' + f.properties[key]);
      parameters += '&' + key.replace(/\ /g, '_') + '=' + f.properties[key];
    }
    url +=
      parameters.replace(/\ /g, '%20') + " target='_blank'>Growth analysis</a>";
    out.push(url);
    var url2 =
      '<a href=/uas_tools/variety_analysis/index.php?crop=Wheat&year=2021&location=Amarillo&sublocation=Irrigation';
    url2 += " target='_blank'>Variety analysis</a>";
    out.push(url2);
    l.bindPopup(out.join('<br />'));
  }
}

我正在尝试使用 out.push(key+": "+f.properties[key].toFixed(2)); 但它不起作用。

这是 geoJSON 文件结构

{ "type": "Feature", "properties": { "Row name": "row-1", "Col": "1", "plot_num": "?436", "plot_name": "?AOBS", "join_key": "?AOBS?436", "CC201014": 0.0, "CC201104": 0.0016344676538850001, "CC201120": 0.56401258728343395, "CC201217": 8.3524346613304221, "CC210113": 7.7746312091202094, "CC210224": 9.7393145428079926, "CC210303": 7.673018393542411, "CC210311": 14.576431943872961, "CC210323": 31.081778483525209, "CC210331": 30.067189249720045, "CC210408": 62.738628486108894, "CC210412": 63.94711538461538, "CC210418": 73.721694264987974, "CC210423": 70.039654826897262, "CC210430": 98.045130406889243, "CC210504": 91.969625530436502, "CC210510": 93.321666364934728, "CC210517": 85.521939491083955, "CC210525": 88.782478347768162, "CC210601": 95.859434682964093, "CC210607": 15.974798327739503, "CC210610": 0.0085470085470090006, "CC210614": 0.0, "CC210617": 0.0 }

toFixed() 方法仅适用于浮点数,看来您可能有一个字符串。您可以先将其解析为浮点数。

out.push(key + ': ' + parseFloat(f.properties[key]).toFixed(2));

单线不是你的朋友。 JavaScript 对优先级有自己的想法。要强制“操作顺序”,请在任何重要组周围使用括号。即使这样,代码编辑器也可能会格式化、美化或删除括号。祝你好运找到错误!最好将任何复杂操作隔离在命名变量中。命名变量更具描述性,更易于阅读和重用。

似乎代码正在对所有值调用 toFixed,即使该值是一个字符串。

for (key in f.properties) {
    //The first few prperties are strings, this is throwing an error as String.prototype.toFixed is not defined, so you can't call it.
    out.push(key + ': ' + parseFloat(f.properties[key]).toFixed(2));
    parameters += '&' + key.replace(/\ /g, '_') + '=' + f.properties[key];
}

试试这个

for (var key in f.properties) {//include var to not add key to global scope
    var val = f.properties[key]
    if (typeof val === "number") {val = val.toFixed(2)}
    out.push(key + ': ' + val);
    parameters += '&' + key.replace(/\ /g, '_') + '=' + val;
}

此外,如其他答案所述,带浮点数的值可能仍然是字符串,如果是这种情况,您可以尝试:

for (var key in f.properties) {//include var to not add key to global scope
    var val = f.properties[key]
    if (Number.isNaN(Number(val))) val = Number(val).toFixed(2)
    out.push(key + ': ' + val);
    parameters += '&' + key.replace(/\ /g, '_') + '=' + val;
}

您也可以使用 Array.reduce() 方法:

var out = Object.keys(f.properties)
  .reduce((a, c) => (typeof f.properties[c] === `number` ?
    a.push(`${c}: ${f.properties[c].toFixed(2)}`) :
    a.push(`${c.replace(/\s/, `_`).toLowerCase()}: ${f.properties[c]}`), a), [])

const f = {
  "type": "Feature",
  "properties": {
    "Row name": "row-1",
    "Col": "1",
    "plot_num": "?436",
    "plot_name": "?AOBS",
    "join_key": "?AOBS?436",
    "CC201014": 0.0,
    "CC201104": 0.0016344676538850001,
    "CC201120": 0.56401258728343395,
    "CC201217": 8.3524346613304221,
    "CC210113": 7.7746312091202094,
    "CC210224": 9.7393145428079926,
    "CC210303": 7.673018393542411,
    "CC210311": 14.576431943872961,
    "CC210323": 31.081778483525209,
    "CC210331": 30.067189249720045,
    "CC210408": 62.738628486108894,
    "CC210412": 63.94711538461538,
    "CC210418": 73.721694264987974,
    "CC210423": 70.039654826897262,
    "CC210430": 98.045130406889243,
    "CC210504": 91.969625530436502,
    "CC210510": 93.321666364934728,
    "CC210517": 85.521939491083955,
    "CC210525": 88.782478347768162,
    "CC210601": 95.859434682964093,
    "CC210607": 15.974798327739503,
    "CC210610": 0.0085470085470090006,
    "CC210614": 0.0,
    "CC210617": 0.0
  }
};
const urls = [
  `/uas_tools/crop_analysis/index.php`,
  `/uas_tools/variety_analysis/index.php`
];

const div = document.createElement('div');

Object.keys(f.properties)
  .reduce((a, c) => (typeof f.properties[c] === `number` ?
    a.push(`${c}: ${f.properties[c].toFixed(2)}`) :
    a.push(`${c.replace(/\s/, `_`).toLowerCase()}: ${f.properties[c]}`), a), [])
  .map(el => {
    const br = document.createElement('br');
    const span = document.createElement('span');
    span.innerText = el;
    div.appendChild(span).appendChild(br);
  });

const parameters = {
  crop: `Wheat`,
  year: 2021,
  location: `Amarillo`,
  sublocation: `Irrigation`
};

urls.map(pathName => {
  const url = new URL(pathName, window.location.origin);
  Object.keys(parameters)
    .map(elem => url.searchParams.set(elem, parameters[elem]));
  const br = document.createElement('br');
  const a = document.createElement('a');
  a.href = url.toString();
  a.target = `_blank`;
  a.innerText = url.pathname
    .split(`/`)
    .slice(-2, -1)[0]
    .split(`_`)
    .map(el => el.charAt(0).toUpperCase() + el.substr(1).toLowerCase())
    .join(` `);
  div.appendChild(a).appendChild(br);
});

document.querySelector(`body`).appendChild(div);
body {
  font-family: sans-serif;
  font-size: 12px;
}