在 JavaScript 中为大于一千的数字添加逗号

JD *_*ill 1 javascript

我正在构建一个融资计算器,所有输出到 DOM 的数字都以数千计。

我目前在我的代码中的一个数字上使用 .toLocaleString() ,并且它有效(主要的 productPrice 数字)。我在输出到 DOM 时使用了 .toLocatelString()。

但是,我似乎无法弄清楚为什么在使用相同的方式时,它不适用于其他数字。具体来说,首付、总额和每月数字。

这是 JS 代码(我输入的代码 .toLocaleString() 在最底部):

"use strict";

// Define product price / tax

const productPrice = 105000;
const tax = 0.13;

// Append product price to DOM

const productPriceID = document.getElementById("product-price");
productPriceID.innerHTML = productPrice.toLocaleString();

// Grab the id's of the main product price, down payment, total, per month and button for DOM appending

const downPaymentValue = document.getElementById("down-payment-value");
const totalValue = document.getElementById("total-value");
const perMonthValue = document.getElementById("per-month-value");
const calculateBtn = document.getElementById("calculate");

///////// Calculations

calculateBtn.addEventListener("click", calculate);

function calculate() {
  // Grab the value of the month selected
  const monthSelected = document.querySelector('input[name="month"]:checked')
    .value;
  // Grab the value of the down payment percentage selected
  const percentageSelected = document.querySelector(
    'input[name="percent"]:checked'
  ).value;
  // Calculate down payment percentage based on main price
  const totalDownPayment = (productPrice * percentageSelected).toFixed(2);
  // Calculate the total
  const totalPrice = (productPrice - totalDownPayment).toFixed(2);
  // Calculate the per month
  const perMonth = (totalPrice / monthSelected).toFixed(2);
  // Append down payment to DOM
  downPaymentValue.innerHTML =
    "<sup>$</sup>" + totalDownPayment.toLocaleString();
  downPaymentValue.parentNode.appendChild(downPaymentValue);
  // Append total to DOM
  totalValue.innerHTML = "<sup>$</sup>" + totalPrice.toLocaleString();
  totalValue.parentNode.appendChild(totalValue);
  // Append per month to DOM
  perMonthValue.innerHTML = "<sup>$</sup>" + perMonth.toLocaleString();
  perMonthValue.parentNode.appendChild(perMonthValue);
}
Run Code Online (Sandbox Code Playgroud)

任何的想法?提前致谢。

Bra*_*don 6

这是因为您的其他数字正在通过toFixed. 所以toLocaleString什么都不做。

用数字完成所有数学运算,最后转换为字符串。

const totalDownPayment = (productPrice * percentageSelected);
const totalPrice = (productPrice - totalDownPayment);
const perMonth = (totalPrice / monthSelected);
Run Code Online (Sandbox Code Playgroud)

使用选项参数转换为文本以指定小数位数:

const totalDownPaymentStr = totalDownPayment.toLocaleString(navigator.language, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
const totalPriceStr = totalPrice.toLocaleString(navigator.language, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
// ...
Run Code Online (Sandbox Code Playgroud)

有关options 参数的更多信息,请参阅MDN 文档