将整数输入转换为单词 [英] converting integer input to words
问题描述
我必须编写一个程序,以便我给它一个三位数的输入并将其转换为文字格式.例子:
I have to write a program such that I give it a three digit input and it converts it into word format. example:
input = 907
output = nine hundred seven
我可以很容易地弄清楚如何给出百位输出.我可以将输入除以 100,然后将结果的整个部分存储到一个新变量中.然后如果变量有值,假设 7
创建另一个字符类型的新变量,并使用 if 条件给它一个值 seven
.
I can easily figure out how to give the hundred position output. I can divide the input by 100 and then store the whole part of result into a new variable. and then if the variable has value, let's say 7
make another new variable of character type and give it a value seven
using if conditionals.
但我不知道该怎么办.我的意思是当有一个像 907
这样的数字时,我是否写了一些东西以便它给我正确的输出.PS 我刚开始编程,不知道这样做的最佳方法.
But I can't figure out what to do for tens and ones. I mean when there is a number like 907
, do I write something so that it gives me the correct output.
PS I just started programming and don't know the best method to do this.
处理这个问题的正确方法是什么?
What is the correct way to handle this?
推荐答案
我用这个:
// Convert numbers to words
// copyright 25th July 2006, by Stephen Chapman http://javascript.about.com
// permission to use this Javascript on your web page is granted
// provided that all of the code (including this copyright notice) is
// used exactly as shown (you can change the numbering system if you wish)
// American Numbering System
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];
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 convertNumberToString(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, ' ');
}
这篇关于将整数输入转换为单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!