【问题标题】:How do I make this check writing function support any number over 1000?如何使此支票书写功能支持超过 1000 的任何数字?
【发布时间】:2022-12-05 21:18:14
【问题描述】:

这是功能:

function generateCheckText(amount) {
  // Convert the dollar amount to a string and split it into parts
  // by the decimal point
  const parts = amount.toString().split('.');

  // Convert the dollar amount to a written out number in English
  let writtenAmount = convertToWrittenNumber(parts[0]);

  // If there are cents, add them to the written amount
  if (parts.length > 1) {
    writtenAmount += ` and ${convertToWrittenNumber(parts[1])} cents`;
  }

  // Return the generated check text
  return `Pay to the order of [Payee] the sum of ${writtenAmount} dollars.`;
}

// Helper function to convert a number to its written out form in English
function convertToWrittenNumber(number) {
  // Array of English words for the different units of numbers
  const units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

  // Array of English words for the different tens places of numbers
  const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

  // Array of English words for the different teens of numbers
  const teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];

  // If the number is zero, return the word for zero
  if (number === 0) {
    return 'zero';
  }

  // If the number is less than ten, return the word for the units place
  if (number < 10) {
    return units[number];
  }

  // If the number is less than 20, return the word for the teen
  if (number < 20) {
    return teens[number - 10];
  }

  // If the number is less than 100, return the word for the tens place and the units place
  if (number < 100) {
    return `${tens[Math.floor(number / 10)]} ${units[number % 10]}`;
  }

  // If the number is greater than or equal to 100, return the word for the units place,
  // the word for the tens place, and the word for the hundreds place
  return `${units[Math.floor(number / 100)]} hundred ${convertToWrittenNumber(number % 100)}`;
}

console.log(generateCheckText(1174.30));

它只适用于 1000 以下的数字。我需要它来支持任何金额。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    https://www.npmjs.com/package/to-words [使用这个库] 不要试图实施已经完成的事情

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 1970-01-01
      • 2017-11-26
      • 2018-08-30
      • 2015-12-20
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多