将美元金额动态转换为文本以包含“美元”和“美分”一词

2024-05-06

我需要将输入字段中输入的美元金额动态转换为文本。我能找到的最接近的解决方案几乎可以满足我的需求,但是,我希望结果文本包含“美元”一词,并删除句子末尾带有“美分”的“点”一词。

这是起始原型和当前结果:

function amountToWords(amountInDigits){
// American Numbering System
var th = ['','thousand','million', 'billion','trillion'];

var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function toWords(s){
  s = s.toString();
  s = s.replace(/[\, ]/g,'');
  if (s != parseFloat(s))
  return 'not a number';
  var x = s.indexOf('.');
  if (x == -1) x = s.length;
  if (x > 15) return 'too big';
  var n = s.split('');
  var str = '';
  var sk = 0;
  for (var i=0; i < x; i++){
    if ((x-i)%3==2){
      if (n[i] == '1') {
        str += tn[Number(n[i+1])] + ' ';
        i++; sk=1;
      } else if (n[i]!=0) {
          str += tw[n[i]-2] + ' ';sk=1;
        }
      } else if (n[i]!=0) {
        str += dg[n[i]] +' ';
        if ((x-i)%3==0)
        str += 'hundred ';
        sk=1;
      } if ((x-i)%3==1) {
        if (sk) str += th[(x-i-1)/3] + ' ';sk=0;
      }
    }
    if (x != s.length) {
      var y = s.length;
      str += 'point ';
      for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
    }
    return str.replace(/\s+/g,' ');
  }

  return toWords(amountInDigits);

}

<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=amountToWords(this.value)" />

因此,如果用户在输入框中输入金额 1234.56 美元,则所需的文本输出将拼写为“一千二百三十四美元五十六美分”

有什么建议么?


详细信息在下面的示例中注释

/*
These arrays are indexed to the number that each element represents
*/
const ones = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine '];
const teen = ['ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
const tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
const high = ['hundred ', 'thousand ', 'million ', 'billion '];
// Helper function - a simple logger
const log = data => console.log(data);

/*
This function takes 2 numbers and matches the first parameter to the index of the 
tens or teen array. The second parameter matches to the index of the ones array. 
A word number between 1 and 99 is returned. 
*/
const tensOnes = (t, o) => +t == 0 ? ones[+o] : +t == 1 ? teen[+o] : +t > 1 && +o == 0 ? tens[+t - 2] : tens[+t - 2] + '-' + ones[+o];

// function takes a number and returns a string number with 2 decimals
const fltN = float => [...parseFloat(float).toFixed(2)];

/* 
This function takes an array created by moneyToEng() function and returns a word
version of the given number. A switch() with 10 cases (9,999,999,999 is max) is 
used to call tensOnes() function. Before the string is returned, there are a few
fixes to make it grammatically correct.
*/
const stepper = array => {
  const D = array[0];
  const C = array[1];
  let size = D.length;
  let word;
  switch (size) {
    case 0:
      word = C;
      break;
    case 1:
      word = tensOnes(0, D[0]) + 'dollars ' + C;
      break;
    case 2:
      word = tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 3:
      word = tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 4:
      word = tensOnes(0, D[3]) + high[1] + tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 5:
      word = tensOnes(D[4], D[3]) + high[1] + tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 6:
      word = tensOnes(0, D[5]) + high[0] + tensOnes(D[4], D[3]) + high[1] + tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 7:
      word = tensOnes(0, D[6]) + high[2] + tensOnes(0, D[5]) + high[0] + tensOnes(D[4], D[3]) + high[1] + tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 8:
      word = tensOnes(D[7], D[6]) + high[2] + tensOnes(0, D[5]) + high[0] + tensOnes(D[4], D[3]) + high[1] + tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 9:
      word = tensOnes(0, D[8]) + high[0] + tensOnes(D[7], D[6]) + high[2] + tensOnes(0, D[5]) + high[0] + tensOnes(D[4], D[3]) + high[1] + tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    case 10:
      word = tensOnes(0, D[9]) + high[3] + tensOnes(0, D[8]) + high[0] + tensOnes(D[7], D[6]) + high[2] + tensOnes(0, D[5]) + high[0] + tensOnes(D[4], D[3]) + high[1] + tensOnes(0, D[2]) + high[0] + tensOnes(D[1], D[0]) + 'dollars ' + C;
      break;
    default:
      break;
  }
  word = word.trim();
  word = word == 'one dollars' ? 'one dollar' : word == 'dollars and one cent' ? 'one cent' : word == 'one dollars and one cent' ? 'one dollar and one cent' : word == 'and undefined-undefinedcents' ? '' : word;
  word = word.replace(/(thousand|million)\s(hundred)/g, '$1').replace(/(million)\s(thousand)/g, '$1').replace(/(tycents)/g, 'ty cents').replace(/(tydollars)/g, 'ty dollars');
  return word;
};

/*
This takes a number and returns a string of words that represent the given 
number as money. It prepares the input for further processing by the stepper() 
function.
*/
const moneyToEng = number => {
  let R = fltN(number);
  let dec, c, cents;
  dec = R.splice(-3, 3);
  c = tensOnes(dec[1], dec[2]);
  cents = c == 'one ' ? 'and one cent' : c == '' ? '' : `and ${c}cents`;
  return stepper([R.reverse(), cents]);
};

// Reference the form
const form = document.forms[0];

// Bind form listen for input event
form.addEventListener('input', dataManager);

// Pass the Event Object
function dataManager(e) {
  /*
  All of form's form controls which is every element in this simple layout.
  */
  const io = this.elements;
  // The fieldset typed into
  const input = e.target;
  // if you are typing into #editor...
  if (input.matches('#editor')) {
    /*
    ...get the text of #editor and have it converted to words by moneyToEng()
    */
    let txt = moneyToEng(input.textContent);
    // Display on #mirror
    io.mirror.textContent = txt;
  }
};
/*
log('100.23 \n'+ moneyToEng(100.23));
log('5600 \n'+moneyToEng(5600));
log('900000003.58 \n'+ moneyToEng(900000003.58));
log('1 \n'+moneyToEng(1));
log('.01 \n'+moneyToEng(.01));
log('1111111111.11 \n'+moneyToEng(1111111111.11));
*/
form {
  font: 2ch/1.15 Consolas;
}

#editor {
  min-height: 2.15ch;
  padding-top: 1.5ch;
  background: lightgrey;
  color: #930;
}

#editor::before {
  content: '$';
}

#mirror {
  min-height: 2.15ch;
}
<form>
  <fieldset>
    <legend>Enter an Amount in USD</legend>
    <fieldset id='editor' contenteditable></fieldset>
    <fieldset id='mirror'></fieldset>
  </fieldset>
</form>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将美元金额动态转换为文本以包含“美元”和“美分”一词 的相关文章

随机推荐

  • Django检查用户组权限

    我有一个名称 的自定义权限可以显示分发页面 代号 can show distribute page 内容类型 User 我添加两个组 名为 manager and normal 一个拥有所引用的许可 一个没有 如何判断用户是否有该权限 我尝
  • 为什么json序列化器不符合多态性?

    我在 NET 4 5 Windows 应用商店应用程序中使用库存 JSON 序列化器 System Runtime Serialization Json DataContractJsonSerializer 我有一个由 API 提供商提供的
  • 使用math.random在java中进行猜谜游戏

    您好 我正在尝试使用 Math random 生成 0 到 100 之间的随机数 然后要求用户输入 0 到 100 之间的数字 或 1 退出 如果数字超出范围 且不是 1 请要求用户输入新数字 如果用户没有正确猜出数字 则告诉用户随机数是否
  • 如何防止Excel单元格中前导零自动截断

    如果我粘贴04562 它会自动截断前导零并将其存储为4562 我希望将其存储为04562 如果您使用 MS Excel 编辑需要存储带前导零的数字的单元格 只需将单元格内容格式化并定义为文本即可 如果您以编程方式存储它 则可以将该值放在引号
  • Ruby 安装由于缺少扩展而中止:openssl、readline、zlib 编译错误

    我正在使用 macOS Catalina 我正在尝试通过 rbenv 安装旧版本的 Ruby 1 9 3 2 1 2 但是 在尝试安装旧版本时 我不断收到以下错误 安装 2 4 或更新版本时没问题 我已经尝试过 brew install o
  • Python 2to3 Windows CMD

    我已经安装了 python 32 包到 C python32 我还设置了路径 Python 路径 C Python32 Lib C Python32 DLLs C Python32 Lib lib tk 路径 C Python32 我想使用
  • 存储DotNetOpenAuth信息和用户信息检索

    这个问题有点结构 设计问题 因为我无法找出执行任务的最佳方法 在我的 MVC 应用程序中 我使用 DotNetOpenAuth 3 4 作为我的登录信息提供程序 并且仅使用标准FormsAuthentication用于饼干等 DB中当前用户
  • 如何像mysql一样对数组进行排序

    如何对与数据库数据相同的数组进行排序 我请求谷歌分析数据 数据是一个大数组 我想将数组与本地数据库中的一些其他字段连接起来 然后我再次扩展大数组 现在我想对大数组进行排序 这与使用我的 sql 相同 如下所示 select from ga
  • 无法加载(查找)j2v8_android_x86 库

    我有一个使用的 gradle 项目j2v8 android 2 2 1 http mvnrepository com artifact com eclipsesource j2v8 j2v8 android 2 2 1库 为 V8 JS 引
  • 不带()的sizeof有什么作用? [复制]

    这个问题在这里已经有答案了 作者是这个问题 https stackoverflow com questions 18898410 2 dimensional array simple understanding当我问他什么时 他只是取笑我s
  • 如何在 Option::and_then 或 Option::map 闭包中使用 async/await 而不使用 OptionFuture?

    我想运行类似以下代码的代码 async fn get user s str gt Option
  • 我如何访问警报内容提供商

    我正在尝试访问警报提供商以获取所有启用的警报信息 所以我写了这个 public static final Uri CONTENT URI Uri parse content com android deskclock alarm Conte
  • 获取 S/MIME 签名邮件的附件

    我正在尝试通过 microsoft graph api 获取签名邮件的附件 I use a GET请求在这个网址上 https graph microsoft com v1 0 me messages AAMkAG attachments
  • 根据标准在多个需求之间分配数量

    我正在创建一个周期盘点表 表 1 将是用户输入 其中将放置找到的材料和数量 表 2 是盘点时的库存快照 我希望将找到的材料数量分配到表 2 上的数量中 直到表 1 的数量用完为止 按照从最新批次 日期代码 到最旧批次 先进先出 的顺序分配数
  • setAnnotation - 无法识别的选择器

    点击搜索按钮后在设备上运行时 我收到此错误 但它在模拟器中工作 2013 03 08 17 58 33 981 IPAD 2661 907 Slider values are min 5000 000000 and max 500000 0
  • CreateProcess error=2,系统找不到指定的文件

    我正在用java编写一个程序 它将执行winrar并解压一个jar文件 放在h myjar jar进入文件夹h new 我的java代码是这样的 import java io File import java io IOException
  • MySQL 中两个 Select 查询的结果相减

    我编写了两个 mysql 查询 一个获取一年中特定月份的总用户 注册 另一个获取一年中特定月份的活跃用户 我需要找到数量inactive当年的用户 为此 我正在考虑减去通过两个单独的查询获得的总用户数和活动用户列 以下是查询 1 Fetch
  • 如何在android listview或线性布局中动态设置marginBottom?

    friends 我想使用java代码或动态设置layout marginBottom 在列表视图或线性布局中 有人指导我如何实现这一目标吗 任何帮助 将不胜感激 ListView lst getListView LinearLayout L
  • 如何开始使用“scipy”

    我之前安装过 Python 3 4 2 和 3 5 2 在这两种情况下 我都可以在 Idle 中涉足编写和测试代码 这给了我两个窗口 一个用于代码的 运行 窗口 一个用于交互和测试的 Shell 窗口 输出 抱歉 不确定术语是否正确 现在我
  • 将美元金额动态转换为文本以包含“美元”和“美分”一词

    我需要将输入字段中输入的美元金额动态转换为文本 我能找到的最接近的解决方案几乎可以满足我的需求 但是 我希望结果文本包含 美元 一词 并删除句子末尾带有 美分 的 点 一词 这是起始原型和当前结果 function amountToWord