/**
* This class will convert numeric values into an english representation
*
* For units, see : http://www.jimloy.com/math/billion.htm
*
* @author yanick.rochon@gmail.com
*/
public class NumberToWords {
static public class ScaleUnit {
private int exponent;
private String[] names;
private ScaleUnit(int exponent, String...names) {
this.exponent = exponent;
this.names = names;
}
public int getExponent() {
return exponent;
}
public String getName(int index) {
return names[index];
}
}
/**
* See http://www.wordiq.com/definition/Names_of_large_numbers
*/
static private ScaleUnit[] SCALE_UNITS = new ScaleUnit[] {
new ScaleUnit(63, "vigintillion", "decilliard"),
new ScaleUnit(60, "novemdecillion", "decillion"),
new ScaleUnit(57, "octodecillion", "nonilliard"),
new ScaleUnit(54, "septendecillion", "nonillion"),
new ScaleUnit(51, "sexdecillion", "octilliard"),
new ScaleUnit(48, "quindecillion", "octillion"),
new ScaleUnit(45, "quattuordecillion", "septilliard"),
new ScaleUnit(42, "tredecillion", "septillion"),
new ScaleUnit(39, "duodecillion", "sextilliard"),
new ScaleUnit(36, "undecillion", "sextillion"),
new ScaleUnit(33, "decillion", "quintilliard"),
new ScaleUnit(30, "nonillion", "quintillion"),
new ScaleUnit(27, "octillion", "quadrilliard"),
new ScaleUnit(24, "septillion", "quadrillion"),
new ScaleUnit(21, "sextillion", "trilliard"),
new ScaleUnit(18, "quintillion", "trillion"),
new ScaleUnit(15, "quadrillion", "billiard"),
new ScaleUnit(12, "trillion", "billion"),
new ScaleUnit(9, "billion", "milliard"),
new ScaleUnit(6, "million", "million"),
new ScaleUnit(3, "thousand", "thousand"),
new ScaleUnit(2, "hundred", "hundred"),
//new ScaleUnit(1, "ten", "ten"),
//new ScaleUnit(0, "one", "one"),
new ScaleUnit(-1, "tenth", "tenth"),
new ScaleUnit(-2, "hundredth", "hundredth"),
new ScaleUnit(-3, "thousandth", "thousandth"),
new ScaleUnit(-4, "ten-thousandth", "ten-thousandth"),
new ScaleUnit(-5, "hundred-thousandth", "hundred-thousandth"),
new ScaleUnit(-6, "millionth", "millionth"),
new ScaleUnit(-7, "ten-millionth", "ten-millionth"),
new ScaleUnit(-8, "hundred-millionth", "hundred-millionth"),
new ScaleUnit(-9, "billionth", "milliardth"),
new ScaleUnit(-10, "ten-billionth", "ten-milliardth"),
new ScaleUnit(-11, "hundred-billionth", "hundred-milliardth"),
new ScaleUnit(-12, "trillionth", "billionth"),
new ScaleUnit(-13, "ten-trillionth", "ten-billionth"),
new ScaleUnit(-14, "hundred-trillionth", "hundred-billionth"),
new ScaleUnit(-15, "quadrillionth", "billiardth"),
new ScaleUnit(-16, "ten-quadrillionth", "ten-billiardth"),
new ScaleUnit(-17, "hundred-quadrillionth", "hundred-billiardth"),
new ScaleUnit(-18, "quintillionth", "trillionth"),
new ScaleUnit(-19, "ten-quintillionth", "ten-trillionth"),
new ScaleUnit(-20, "hundred-quintillionth", "hundred-trillionth"),
new ScaleUnit(-21, "sextillionth", "trilliardth"),
new ScaleUnit(-22, "ten-sextillionth", "ten-trilliardth"),
new ScaleUnit(-23, "hundred-sextillionth", "hundred-trilliardth"),
new ScaleUnit(-24, "septillionth","quadrillionth"),
new ScaleUnit(-25, "ten-septillionth","ten-quadrillionth"),
new ScaleUnit(-26, "hundred-septillionth","hundred-quadrillionth"),
};
static public enum Scale {
SHORT,
LONG;
public String getName(int exponent) {
for (ScaleUnit unit : SCALE_UNITS) {
if (unit.getExponent() == exponent) {
return unit.getName(this.ordinal());
}
}
return "";
}
}
/**
* Change this scale to support American and modern British value (short scale)
* or Traditional British value (long scale)
*/
static public Scale SCALE = Scale.SHORT;
static abstract public class AbstractProcessor {
static protected final String SEPARATOR = " ";
static protected final int NO_VALUE = -1;
protected List<Integer> getDigits(long value) {
ArrayList<Integer> digits = new ArrayList<Integer>();
if (value == 0) {
digits.add(0);
} else {
while (value > 0) {
digits.add(0, (int) value % 10);
value /= 10;
}
}
return digits;
}
public String getName(long value) {
return getName(Long.toString(value));
}
public String getName(double value) {
return getName(Double.toString(value));
}
abstract public String getName(String value);
}
static public class UnitProcessor extends AbstractProcessor {
static private final String[] TOKENS = new String[] {
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
int offset = NO_VALUE;
int number;
if (value.length() > 3) {
number = Integer.valueOf(value.substring(value.length() - 3), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 100;
if (number < 10) {
offset = (number % 10) - 1;
//number /= 10;
} else if (number < 20) {
offset = (number % 20) - 1;
//number /= 100;
}
if (offset != NO_VALUE && offset < TOKENS.length) {
buffer.append(TOKENS[offset]);
}
return buffer.toString();
}
}
static public class TensProcessor extends AbstractProcessor {
static private final String[] TOKENS = new String[] {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
static private final String UNION_SEPARATOR = "-";
private UnitProcessor unitProcessor = new UnitProcessor();
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
boolean tensFound = false;
int number;
if (value.length() > 3) {
number = Integer.valueOf(value.substring(value.length() - 3), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 100; // keep only two digits
if (number >= 20) {
buffer.append(TOKENS[(number / 10) - 2]);
number %= 10;
tensFound = true;
} else {
number %= 20;
}
if (number != 0) {
if (tensFound) {
buffer.append(UNION_SEPARATOR);
}
buffer.append(unitProcessor.getName(number));
}
return buffer.toString();
}
}
static public class HundredProcessor extends AbstractProcessor {
private int EXPONENT = 2;
private UnitProcessor unitProcessor = new UnitProcessor();
private TensProcessor tensProcessor = new TensProcessor();
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
int number;
if (value.isEmpty()) {
number = 0;
} else if (value.length() > 4) {
number = Integer.valueOf(value.substring(value.length() - 4), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 1000; // keep at least three digits
if (number >= 100) {
buffer.append(unitProcessor.getName(number / 100));
buffer.append(SEPARATOR);
buffer.append(SCALE.getName(EXPONENT));
}
String tensName = tensProcessor.getName(number % 100);
if (!tensName.isEmpty() && (number >= 100)) {
buffer.append(SEPARATOR);
}
buffer.append(tensName);
return buffer.toString();
}
}
static public class CompositeBigProcessor extends AbstractProcessor {
private HundredProcessor hundredProcessor = new HundredProcessor();
private AbstractProcessor lowProcessor;
private int exponent;
public CompositeBigProcessor(int exponent) {
if (exponent <= 3) {
lowProcessor = hundredProcessor;
} else {
lowProcessor = new CompositeBigProcessor(exponent - 3);
}
this.exponent = exponent;
}
public String getToken() {
return SCALE.getName(getPartDivider());
}
protected AbstractProcessor getHighProcessor() {
return hundredProcessor;
}
protected AbstractProcessor getLowProcessor() {
return lowProcessor;
}
public int getPartDivider() {
return exponent;
}
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
String high, low;
if (value.length() < getPartDivider()) {
high = "";
low = value;
} else {
int index = value.length() - getPartDivider();
high = value.substring(0, index);
low = value.substring(index);
}
String highName = getHighProcessor().getName(high);
String lowName = getLowProcessor().getName(low);
if (!highName.isEmpty()) {
buffer.append(highName);
buffer.append(SEPARATOR);
buffer.append(getToken());
if (!lowName.isEmpty()) {
buffer.append(SEPARATOR);
}
}
if (!lowName.isEmpty()) {
buffer.append(lowName);
}
return buffer.toString();
}
}
static public class DefaultProcessor extends AbstractProcessor {
static private String MINUS = "minus";
static private String UNION_AND = "and";
static private String ZERO_TOKEN = "zero";
private AbstractProcessor processor = new CompositeBigProcessor(63);
@Override
public String getName(String value) {
boolean negative = false;
if (value.startsWith("-")) {
negative = true;
value = value.substring(1);
}
int decimals = value.indexOf(".");
String decimalValue = null;
if (0 <= decimals) {
decimalValue = value.substring(decimals + 1);
value = value.substring(0, decimals);
}
String name = processor.getName(value);
if (name.isEmpty()) {
name = ZERO_TOKEN;
} else if (negative) {
name = MINUS.concat(SEPARATOR).concat(name);
}
if (!(null == decimalValue || decimalValue.isEmpty())) {
name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR)
.concat(processor.getName(decimalValue))
.concat(SEPARATOR).concat(SCALE.getName(-decimalValue.length()));
}
return name;
}
}
static public AbstractProcessor processor;
public static void main(String...args) {
processor = new DefaultProcessor();
long[] values = new long[] {
0,
4,
10,
12,
100,
108,
299,
1000,
1003,
2040,
45213,
100000,
100005,
100010,
202020,
202022,
999999,
1000000,
1000001,
10000000,
10000007,
99999999,
Long.MAX_VALUE,
Long.MIN_VALUE
};
String[] strValues = new String[] {
"0001.2",
"3.141592"
};
for (long val : values) {
System.out.println(val + " = " + processor.getName(val) );
}
for (String strVal : strValues) {
System.out.println(strVal + " = " + processor.getName(strVal) );
}
// generate a very big number...
StringBuilder bigNumber = new StringBuilder();
for (int d=0; d<66; d++) {
bigNumber.append( (char) ((Math.random() * 10) + '0'));
}
bigNumber.append(".");
for (int d=0; d<26; d++) {
bigNumber.append( (char) ((Math.random() * 10) + '0'));
}
System.out.println(bigNumber.toString() + " = " + processor.getName(bigNumber.toString()));
}
}
以及一个样本输出(用于随机大数生成器)
0 = zero
4 = four
10 = ten
12 = twelve
100 = one hundred
108 = one hundred eight
299 = two hundred ninety-nine
1000 = one thousand
1003 = one thousand three
2040 = two thousand fourty
45213 = fourty-five thousand two hundred thirteen
100000 = one hundred thousand
100005 = one hundred thousand five
100010 = one hundred thousand ten
202020 = two hundred two thousand twenty
202022 = two hundred two thousand twenty-two
999999 = nine hundred ninety-nine thousand nine hundred ninety-nine
1000000 = one million
1000001 = one million one
10000000 = ten million
10000007 = ten million seven
99999999 = ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine
9223372036854775807 = nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred seven
-9223372036854775808 = minus nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred eight
0001.2 = one and two tenth
3.141592 = three and one hundred fourty-one thousand five hundred ninety-two millionth
694780458103427072928672912656674465845126458162617425283733729646.85695031739734695391404376 = six hundred ninety-four vigintillion seven hundred eighty novemdecillion four hundred fifty-eight octodecillion one hundred three septendecillion four hundred twenty-seven sexdecillion seventy-two quindecillion nine hundred twenty-eight quattuordecillion six hundred seventy-two tredecillion nine hundred twelve duodecillion six hundred fifty-six undecillion six hundred seventy-four decillion four hundred sixty-five nonillion eight hundred fourty-five octillion one hundred twenty-six septillion four hundred fifty-eight sextillion one hundred sixty-two quintillion six hundred seventeen quadrillion four hundred twenty-five trillion two hundred eighty-three billion seven hundred thirty-three million seven hundred twenty-nine thousand six hundred fourty-six and eighty-five septillion six hundred ninety-five sextillion thirty-one quintillion seven hundred thirty-nine quadrillion seven hundred thirty-four trillion six hundred ninety-five billion three hundred ninety-one million four hundred four thousand three hundred seventy-six hundred-septillionth
import java.text.DecimalFormat;
public class EnglishNumberToWords {
private static final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private static final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
private EnglishNumberToWords() {}
private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 < 20){
soFar = numNames[number % 100];
number /= 100;
}
else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) return soFar;
return numNames[number] + " hundred" + soFar;
}
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) { return "zero"; }
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9,12));
String tradBillions;
switch (billions) {
case 0:
tradBillions = "";
break;
case 1 :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
break;
default :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
}
String result = tradBillions;
String tradMillions;
switch (millions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
}
result = result + tradMillions;
String tradHundredThousands;
switch (hundredThousands) {
case 0:
tradHundredThousands = "";
break;
case 1 :
tradHundredThousands = "one thousand ";
break;
default :
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " thousand ";
}
result = result + tradHundredThousands;
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}
/**
* testing
* @param args
*/
public static void main(String[] args) {
System.out.println("*** " + EnglishNumberToWords.convert(0));
System.out.println("*** " + EnglishNumberToWords.convert(1));
System.out.println("*** " + EnglishNumberToWords.convert(16));
System.out.println("*** " + EnglishNumberToWords.convert(100));
System.out.println("*** " + EnglishNumberToWords.convert(118));
System.out.println("*** " + EnglishNumberToWords.convert(200));
System.out.println("*** " + EnglishNumberToWords.convert(219));
System.out.println("*** " + EnglishNumberToWords.convert(800));
System.out.println("*** " + EnglishNumberToWords.convert(801));
System.out.println("*** " + EnglishNumberToWords.convert(1316));
System.out.println("*** " + EnglishNumberToWords.convert(1000000));
System.out.println("*** " + EnglishNumberToWords.convert(2000000));
System.out.println("*** " + EnglishNumberToWords.convert(3000200));
System.out.println("*** " + EnglishNumberToWords.convert(700000));
System.out.println("*** " + EnglishNumberToWords.convert(9000000));
System.out.println("*** " + EnglishNumberToWords.convert(9001000));
System.out.println("*** " + EnglishNumberToWords.convert(123456789));
System.out.println("*** " + EnglishNumberToWords.convert(2147483647));
System.out.println("*** " + EnglishNumberToWords.convert(3000000010L));
/*
*** zero
*** one
*** sixteen
*** one hundred
*** one hundred eighteen
*** two hundred
*** two hundred nineteen
*** eight hundred
*** eight hundred one
*** one thousand three hundred sixteen
*** one million
*** two millions
*** three millions two hundred
*** seven hundred thousand
*** nine millions
*** nine millions one thousand
*** one hundred twenty three millions four hundred
** fifty six thousand seven hundred eighty nine
*** two billion one hundred forty seven millions
** four hundred eighty three thousand six hundred forty seven
*** three billion ten
**/
}
}
法国人
和英语版本有很大的不同,但是法语版本要难得多!
package com.rgagnon.howto;
import java.text.*;
class FrenchNumberToWords {
private static final String[] dizaineNames = {
"",
"",
"vingt",
"trente",
"quarante",
"cinquante",
"soixante",
"soixante",
"quatre-vingt",
"quatre-vingt"
};
private static final String[] uniteNames1 = {
"",
"un",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix",
"onze",
"douze",
"treize",
"quatorze",
"quinze",
"seize",
"dix-sept",
"dix-huit",
"dix-neuf"
};
private static final String[] uniteNames2 = {
"",
"",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix"
};
private FrenchNumberToWords() {}
private static String convertZeroToHundred(int number) {
int laDizaine = number / 10;
int lUnite = number % 10;
String resultat = "";
switch (laDizaine) {
case 1 :
case 7 :
case 9 :
lUnite = lUnite + 10;
break;
default:
}
// séparateur "-" "et" ""
String laLiaison = "";
if (laDizaine > 1) {
laLiaison = "-";
}
// cas particuliers
switch (lUnite) {
case 0:
laLiaison = "";
break;
case 1 :
if (laDizaine == 8) {
laLiaison = "-";
}
else {
laLiaison = " et ";
}
break;
case 11 :
if (laDizaine==7) {
laLiaison = " et ";
}
break;
default:
}
// dizaines en lettres
switch (laDizaine) {
case 0:
resultat = uniteNames1[lUnite];
break;
case 8 :
if (lUnite == 0) {
resultat = dizaineNames[laDizaine];
}
else {
resultat = dizaineNames[laDizaine]
+ laLiaison + uniteNames1[lUnite];
}
break;
default :
resultat = dizaineNames[laDizaine]
+ laLiaison + uniteNames1[lUnite];
}
return resultat;
}
private static String convertLessThanOneThousand(int number) {
int lesCentaines = number / 100;
int leReste = number % 100;
String sReste = convertZeroToHundred(leReste);
String resultat;
switch (lesCentaines) {
case 0:
resultat = sReste;
break;
case 1 :
if (leReste > 0) {
resultat = "cent " + sReste;
}
else {
resultat = "cent";
}
break;
default :
if (leReste > 0) {
resultat = uniteNames2[lesCentaines] + " cent " + sReste;
}
else {
resultat = uniteNames2[lesCentaines] + " cents";
}
}
return resultat;
}
public static String convert(long number) {
// 0 à 999 999 999 999
if (number == 0) { return "zéro"; }
String snumber = Long.toString(number);
// pad des "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int lesMilliards = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int lesMillions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int lesCentMille = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int lesMille = Integer.parseInt(snumber.substring(9,12));
String tradMilliards;
switch (lesMilliards) {
case 0:
tradMilliards = "";
break;
case 1 :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliard ";
break;
default :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliards ";
}
String resultat = tradMilliards;
String tradMillions;
switch (lesMillions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " millions ";
}
resultat = resultat + tradMillions;
String tradCentMille;
switch (lesCentMille) {
case 0:
tradCentMille = "";
break;
case 1 :
tradCentMille = "mille ";
break;
default :
tradCentMille = convertLessThanOneThousand(lesCentMille)
+ " mille ";
}
resultat = resultat + tradCentMille;
String tradMille;
tradMille = convertLessThanOneThousand(lesMille);
resultat = resultat + tradMille;
return resultat;
}
public static void main(String[] args) {
System.out.println("*** " + FrenchNumberToWords.convert(0));
System.out.println("*** " + FrenchNumberToWords.convert(9));
System.out.println("*** " + FrenchNumberToWords.convert(19));
System.out.println("*** " + FrenchNumberToWords.convert(21));
System.out.println("*** " + FrenchNumberToWords.convert(28));
System.out.println("*** " + FrenchNumberToWords.convert(71));
System.out.println("*** " + FrenchNumberToWords.convert(72));
System.out.println("*** " + FrenchNumberToWords.convert(80));
System.out.println("*** " + FrenchNumberToWords.convert(81));
System.out.println("*** " + FrenchNumberToWords.convert(89));
System.out.println("*** " + FrenchNumberToWords.convert(90));
System.out.println("*** " + FrenchNumberToWords.convert(91));
System.out.println("*** " + FrenchNumberToWords.convert(97));
System.out.println("*** " + FrenchNumberToWords.convert(100));
System.out.println("*** " + FrenchNumberToWords.convert(101));
System.out.println("*** " + FrenchNumberToWords.convert(110));
System.out.println("*** " + FrenchNumberToWords.convert(120));
System.out.println("*** " + FrenchNumberToWords.convert(200));
System.out.println("*** " + FrenchNumberToWords.convert(201));
System.out.println("*** " + FrenchNumberToWords.convert(232));
System.out.println("*** " + FrenchNumberToWords.convert(999));
System.out.println("*** " + FrenchNumberToWords.convert(1000));
System.out.println("*** " + FrenchNumberToWords.convert(1001));
System.out.println("*** " + FrenchNumberToWords.convert(10000));
System.out.println("*** " + FrenchNumberToWords.convert(10001));
System.out.println("*** " + FrenchNumberToWords.convert(100000));
System.out.println("*** " + FrenchNumberToWords.convert(2000000));
System.out.println("*** " + FrenchNumberToWords.convert(3000000000L));
System.out.println("*** " + FrenchNumberToWords.convert(2147483647));
/*
*** OUTPUT
*** zéro
*** neuf
*** dix-neuf
*** vingt et un
*** vingt-huit
*** soixante et onze
*** soixante-douze
*** quatre-vingt
*** quatre-vingt-un
*** quatre-vingt-neuf
*** quatre-vingt-dix
*** quatre-vingt-onze
*** quatre-vingt-dix-sept
*** cent
*** cent un
*** cent dix
*** cent vingt
*** deux cents
*** deux cent un
*** deux cent trente-deux
*** neuf cent quatre-vingt-dix-neuf
*** mille
*** mille un
*** dix mille
*** dix mille un
*** cent mille
*** deux millions
*** trois milliards
*** deux milliards cent quarante-sept millions
** quatre cent quatre-vingt-trois mille six cent quarante-sept
*/
}
}
您可以通过两次调用“ return”方法来处理“ Dollar and cent”转换。
String phrase = "12345.67" ;
Float num = new Float( phrase ) ;
int dollars = (int)Math.floor( num ) ;
int cent = (int)Math.floor( ( num - dollars ) * 100.0f ) ;
String s = "$ " + EnglishNumberToWords.convert( dollars ) + " and "
+ EnglishNumberToWords.convert( cent ) + " cents" ;
另一种使用 DBMS 内置函数的方法(如果可用)。
对于 < strong > Oracle
SQL> select to_char(to_date(873,'J'), 'JSP') as converted_form from dual;
CONVERTED_FORM
---------------------------
EIGHT HUNDRED SEVENTY-THREE
SQL>
'JSP' means :
J : the Julian format.
SP : spells the word for the number passed to to_date
Words w = Words.getInstance(1234567);
System.out.println(w.getNumberInWords());
我的程序支持多达1000万。如果你想,你仍然可以扩展这一点。只是低于示例输出
2345223 = Twenty Three Lakh Fourty Five Thousand Two Hundred Twenty Three
9999999 = Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
199 = One Hundred Ninety Nine
10 = Ten
/**
* This class will convert numeric values into an english representation
*
* For units, see : http://www.jimloy.com/math/billion.htm
*
* @author yanick.rochon@gmail.com
*/
public class NumberToWords {
static public class ScaleUnit {
private int exponent;
private String[] names;
private ScaleUnit(int exponent, String... names) {
this.exponent = exponent;
this.names = names;
}
public int getExponent() {
return exponent;
}
public String getName(int index) {
return names[index];
}
}
/**
* See http://www.wordiq.com/definition/Names_of_large_numbers
*/
static private ScaleUnit[] SCALE_UNITS = new ScaleUnit[] {
new ScaleUnit(63, "vigintillion", "decilliard"),
new ScaleUnit(60, "novemdecillion", "decillion"),
new ScaleUnit(57, "octodecillion", "nonilliard"),
new ScaleUnit(54, "septendecillion", "nonillion"),
new ScaleUnit(51, "sexdecillion", "octilliard"),
new ScaleUnit(48, "quindecillion", "octillion"),
new ScaleUnit(45, "quattuordecillion", "septilliard"),
new ScaleUnit(42, "tredecillion", "septillion"),
new ScaleUnit(39, "duodecillion", "sextilliard"),
new ScaleUnit(36, "undecillion", "sextillion"),
new ScaleUnit(33, "decillion", "quintilliard"),
new ScaleUnit(30, "nonillion", "quintillion"),
new ScaleUnit(27, "octillion", "quadrilliard"),
new ScaleUnit(24, "septillion", "quadrillion"),
new ScaleUnit(21, "sextillion", "trilliard"),
new ScaleUnit(18, "quintillion", "trillion"),
new ScaleUnit(15, "quadrillion", "billiard"),
new ScaleUnit(12, "trillion", "billion"),
new ScaleUnit(9, "billion", "milliard"),
new ScaleUnit(6, "million", "million"),
new ScaleUnit(3, "thousand", "thousand"),
new ScaleUnit(2, "hundred", "hundred"),
// new ScaleUnit(1, "ten", "ten"),
// new ScaleUnit(0, "one", "one"),
new ScaleUnit(-1, "tenth", "tenth"), new ScaleUnit(-2, "hundredth", "hundredth"),
new ScaleUnit(-3, "thousandth", "thousandth"),
new ScaleUnit(-4, "ten-thousandth", "ten-thousandth"),
new ScaleUnit(-5, "hundred-thousandth", "hundred-thousandth"),
new ScaleUnit(-6, "millionth", "millionth"),
new ScaleUnit(-7, "ten-millionth", "ten-millionth"),
new ScaleUnit(-8, "hundred-millionth", "hundred-millionth"),
new ScaleUnit(-9, "billionth", "milliardth"),
new ScaleUnit(-10, "ten-billionth", "ten-milliardth"),
new ScaleUnit(-11, "hundred-billionth", "hundred-milliardth"),
new ScaleUnit(-12, "trillionth", "billionth"),
new ScaleUnit(-13, "ten-trillionth", "ten-billionth"),
new ScaleUnit(-14, "hundred-trillionth", "hundred-billionth"),
new ScaleUnit(-15, "quadrillionth", "billiardth"),
new ScaleUnit(-16, "ten-quadrillionth", "ten-billiardth"),
new ScaleUnit(-17, "hundred-quadrillionth", "hundred-billiardth"),
new ScaleUnit(-18, "quintillionth", "trillionth"),
new ScaleUnit(-19, "ten-quintillionth", "ten-trillionth"),
new ScaleUnit(-20, "hundred-quintillionth", "hundred-trillionth"),
new ScaleUnit(-21, "sextillionth", "trilliardth"),
new ScaleUnit(-22, "ten-sextillionth", "ten-trilliardth"),
new ScaleUnit(-23, "hundred-sextillionth", "hundred-trilliardth"),
new ScaleUnit(-24, "septillionth", "quadrillionth"),
new ScaleUnit(-25, "ten-septillionth", "ten-quadrillionth"),
new ScaleUnit(-26, "hundred-septillionth", "hundred-quadrillionth"), };
static public enum Scale {
SHORT, LONG;
public String getName(int exponent) {
for (ScaleUnit unit : SCALE_UNITS) {
if (unit.getExponent() == exponent) {
return unit.getName(this.ordinal());
}
}
return "";
}
}
/**
* Change this scale to support American and modern British value (short scale) or Traditional
* British value (long scale)
*/
static public Scale SCALE = Scale.SHORT;
static abstract public class AbstractProcessor {
static protected final String SEPARATOR = " ";
static protected final int NO_VALUE = -1;
protected List<Integer> getDigits(long value) {
ArrayList<Integer> digits = new ArrayList<Integer>();
if (value == 0) {
digits.add(0);
} else {
while (value > 0) {
digits.add(0, (int) value % 10);
value /= 10;
}
}
return digits;
}
public String getName(long value) {
return getName(Long.toString(value));
}
public String getName(double value) {
return getName(Double.toString(value));
}
abstract public String getName(String value);
}
static public class UnitProcessor extends AbstractProcessor {
static private final String[] TOKENS = new String[] { "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
int offset = NO_VALUE;
int number;
if (value.length() > 3) {
number = Integer.valueOf(value.substring(value.length() - 3), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 100;
if (number < 10) {
offset = (number % 10) - 1;
// number /= 10;
} else if (number < 20) {
offset = (number % 20) - 1;
// number /= 100;
}
if (offset != NO_VALUE && offset < TOKENS.length) {
buffer.append(TOKENS[offset]);
}
return buffer.toString();
}
}
static public class TensProcessor extends AbstractProcessor {
static private final String[] TOKENS = new String[] { "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
static private final String UNION_SEPARATOR = "-";
private UnitProcessor unitProcessor = new UnitProcessor();
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
boolean tensFound = false;
int number;
if (value.length() > 3) {
number = Integer.valueOf(value.substring(value.length() - 3), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 100; // keep only two digits
if (number >= 20) {
buffer.append(TOKENS[(number / 10) - 2]);
number %= 10;
tensFound = true;
} else {
number %= 20;
}
if (number != 0) {
if (tensFound) {
buffer.append(UNION_SEPARATOR);
}
buffer.append(unitProcessor.getName(number));
}
return buffer.toString();
}
}
static public class HundredProcessor extends AbstractProcessor {
private int EXPONENT = 2;
private UnitProcessor unitProcessor = new UnitProcessor();
private TensProcessor tensProcessor = new TensProcessor();
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
int number;
if ("".equals(value)) {
number = 0;
} else if (value.length() > 4) {
number = Integer.valueOf(value.substring(value.length() - 4), 10);
} else {
number = Integer.valueOf(value, 10);
}
number %= 1000; // keep at least three digits
if (number >= 100) {
buffer.append(unitProcessor.getName(number / 100));
buffer.append(SEPARATOR);
buffer.append(SCALE.getName(EXPONENT));
}
String tensName = tensProcessor.getName(number % 100);
if (!"".equals(tensName) && (number >= 100)) {
buffer.append(SEPARATOR);
}
buffer.append(tensName);
return buffer.toString();
}
}
static public class CompositeBigProcessor extends AbstractProcessor {
private HundredProcessor hundredProcessor = new HundredProcessor();
private AbstractProcessor lowProcessor;
private int exponent;
public CompositeBigProcessor(int exponent) {
if (exponent <= 3) {
lowProcessor = hundredProcessor;
} else {
lowProcessor = new CompositeBigProcessor(exponent - 3);
}
this.exponent = exponent;
}
public String getToken() {
return SCALE.getName(getPartDivider());
}
protected AbstractProcessor getHighProcessor() {
return hundredProcessor;
}
protected AbstractProcessor getLowProcessor() {
return lowProcessor;
}
public int getPartDivider() {
return exponent;
}
@Override
public String getName(String value) {
StringBuilder buffer = new StringBuilder();
String high, low;
if (value.length() < getPartDivider()) {
high = "";
low = value;
} else {
int index = value.length() - getPartDivider();
high = value.substring(0, index);
low = value.substring(index);
}
String highName = getHighProcessor().getName(high);
String lowName = getLowProcessor().getName(low);
if (!"".equals(highName)) {
buffer.append(highName);
buffer.append(SEPARATOR);
buffer.append(getToken());
if (!"".equals(lowName)) {
buffer.append(SEPARATOR);
}
}
if (!"".equals(lowName)) {
buffer.append(lowName);
}
return buffer.toString();
}
}
static public class DefaultProcessor extends AbstractProcessor {
static private String MINUS = "minus";
static private String UNION_AND = "and";
static private String ZERO_TOKEN = "zero";
private AbstractProcessor processor = new CompositeBigProcessor(63);
@Override
public String getName(String value) {
boolean negative = false;
if (value.startsWith("-")) {
negative = true;
value = value.substring(1);
}
int decimals = value.indexOf(".");
String decimalValue = null;
if (0 <= decimals) {
decimalValue = value.substring(decimals + 1);
value = value.substring(0, decimals);
}
String name = processor.getName(value);
if ("".equals(name)) {
name = ZERO_TOKEN;
} else if (negative) {
name = MINUS.concat(SEPARATOR).concat(name);
}
if (!(null == decimalValue || "".equals(decimalValue))) {
String zeroDecimalValue = "";
for (int i = 0; i < decimalValue.length(); i++) {
zeroDecimalValue = zeroDecimalValue + "0";
}
if (decimalValue.equals(zeroDecimalValue)) {
name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR).concat(
"zero").concat(SEPARATOR).concat(
SCALE.getName(-decimalValue.length()));
} else {
name = name.concat(SEPARATOR).concat(UNION_AND).concat(SEPARATOR).concat(
processor.getName(decimalValue)).concat(SEPARATOR).concat(
SCALE.getName(-decimalValue.length()));
}
}
return name;
}
}
static public AbstractProcessor processor;
public static void main(String... args) {
processor = new DefaultProcessor();
long[] values = new long[] { 0, 4, 10, 12, 100, 108, 299, 1000, 1003, 2040, 45213, 100000,
100005, 100010, 202020, 202022, 999999, 1000000, 1000001, 10000000, 10000007,
99999999, Long.MAX_VALUE, Long.MIN_VALUE };
String[] strValues = new String[] { "0", "1.30", "0001.00", "3.141592" };
for (long val : values) {
System.out.println(val + " = " + processor.getName(val));
}
for (String strVal : strValues) {
System.out.println(strVal + " = " + processor.getName(strVal));
}
// generate a very big number...
StringBuilder bigNumber = new StringBuilder();
for (int d = 0; d < 66; d++) {
bigNumber.append((char) ((Math.random() * 10) + '0'));
}
bigNumber.append(".");
for (int d = 0; d < 26; d++) {
bigNumber.append((char) ((Math.random() * 10) + '0'));
}
System.out.println(bigNumber.toString() + " = " + processor.getName(bigNumber.toString()));
}
}
输出是
0 = zero
4 = four
10 = ten
12 = twelve
100 = one hundred
108 = one hundred eight
299 = two hundred ninety-nine
1000 = one thousand
1003 = one thousand three
2040 = two thousand fourty
45213 = fourty-five thousand two hundred thirteen
100000 = one hundred thousand
100005 = one hundred thousand five
100010 = one hundred thousand ten
202020 = two hundred two thousand twenty
202022 = two hundred two thousand twenty-two
999999 = nine hundred ninety-nine thousand nine hundred ninety-nine
1000000 = one million
1000001 = one million one
10000000 = ten million
10000007 = ten million seven
99999999 = ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine
9223372036854775807 = nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred seven
-9223372036854775808 = minus nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred eight
0.0 = zero and zero tenth
1.30 = one and thirty hundredth
0001.00 = one and zero hundredth
3.141592 = three and one hundred fourty-one thousand five hundred ninety-two millionth
354064188376576616844741830273568537829518115677552666352927559274.76892492652888527014418647 = three hundred fifty-four vigintillion sixty-four novemdecillion one hundred eighty-eight octodecillion three hundred seventy-six septendecillion five hundred seventy-six sexdecillion six hundred sixteen quindecillion eight hundred fourty-four quattuordecillion seven hundred fourty-one tredecillion eight hundred thirty duodecillion two hundred seventy-three undecillion five hundred sixty-eight decillion five hundred thirty-seven nonillion eight hundred twenty-nine octillion five hundred eighteen septillion one hundred fifteen sextillion six hundred seventy-seven quintillion five hundred fifty-two quadrillion six hundred sixty-six trillion three hundred fifty-two billion nine hundred twenty-seven million five hundred fifty-nine thousand two hundred seventy-four and seventy-six septillion eight hundred ninety-two sextillion four hundred ninety-two quintillion six hundred fifty-two quadrillion eight hundred eighty-eight trillion five hundred twenty-seven billion fourteen million four hundred eighteen thousand six hundred fourty-seven hundred-septillionth
5599908 = 'five million five hundred ninety nine thousand nine hundred eight'
192603486 = 'one hundred ninety two million six hundred three thousand four hundred eighty six'
1392431868 = 'one billion three hundred ninety two million four hundred thirty one thousand eight hundred sixty eight'
1023787010 = 'one billion twenty three million seven hundred eighty seven thousand ten'
1364396236 = 'one billion three hundred sixty four million three hundred ninety six thousand two hundred thirty six'
1511255671 = 'one billion five hundred eleven million two hundred fifty five thousand six hundred seventy one'
225955221 = 'two hundred twenty five million nine hundred fifty five thousand two hundred twenty one'
1890141052 = 'one billion eight hundred ninety million one hundred forty one thousand fifty two'
261839422 = 'two hundred sixty one million eight hundred thirty nine thousand four hundred twenty two'
728428650 = 'seven hundred twenty eight million four hundred twenty eight thousand six hundred fifty'
860607319 = 'eight hundred sixty million six hundred seven thousand three hundred nineteen'
719753587 = 'seven hundred nineteen million seven hundred fifty three thousand five hundred eighty seven'
2063829124 = 'two billion sixty three million eight hundred twenty nine thousand one hundred twenty four'
1081010996 = 'one billion eighty one million ten thousand nine hundred ninety six'
999215799 = 'nine hundred ninety nine million two hundred fifteen thousand seven hundred ninety nine'
2105226236 = 'two billion one hundred five million two hundred twenty six thousand two hundred thirty six'
1431882940 = 'one billion four hundred thirty one million eight hundred eighty two thousand nine hundred forty'
1991707241 = 'one billion nine hundred ninety one million seven hundred seven thousand two hundred forty one'
1088301563 = 'one billion eighty eight million three hundred one thousand five hundred sixty three'
964601609 = 'nine hundred sixty four million six hundred one thousand six hundred nine'
1000 = 'one thousand'
2000 = 'two thousand'
10000 = 'ten thousand'
11000 = 'eleven thousand'
999999999 = 'nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine'
2147483647 = 'two billion one hundred forty seven million four hundred eighty three thousand six hundred forty seven'
package com.stack.overflow.number.in.english;
import java.util.ResourceBundle;
public class ActualImplementation {
public static ResourceBundle readPropertyFile = ResourceBundle
.getBundle("NumberEnglishRepresentation");
public static void main(String[] args) {
System.out.println(ActualImplementation.main(-2));
}
public static String main(Integer number) {
int power;
// Calculate Number of digits
Integer numberOfDigits = number > 0 ? (int) Math.log10((double) number) + 1
: 1;
String output = "";
// If number is negative convert it to positive an append minus to
// output
if (Integer.signum(number) == -1) {
output = "minus ";
number = number < 0 ? number * -1 : number;
}
String stringVal = String.valueOf(number);
if (number <= 20 || number == 30 || number == 40 || number == 50
|| number == 60 || number == 70 || number == 80 || number == 90
|| number == 100 || number == 1000)
output += readPropertyFile.getString(stringVal);
else {
int i;
for (i = 0; i < numberOfDigits; i++) {
if (number != 0) {
numberOfDigits = number > 0 ? (int) Math
.log10((double) number) + 1 : 1;
power = (int) Math.pow(10, numberOfDigits - 1);
// If number is like 10,001 then print ten first and then
// remaining value
if (numberOfDigits >= 5 && numberOfDigits % 2 == 1) {
power = (int) Math.pow(10, numberOfDigits - 2);
}
if (readPropertyFile.containsKey(String.valueOf(number)))
output += readPropertyFile.getString(String
.valueOf(number));
else {
// As the digits at units and tens place are read
// differently
if (numberOfDigits > 2) {
output += readPropertyFile.getString(String
.valueOf(number / power))
+ readPropertyFile.getString(String
.valueOf(power));
} else {
output += readPropertyFile.getString(String
.valueOf(number - number % power));
}
}
number = (int) (number % power);
}
}
}
return output;
}
}
@Test
public void given_a_complex_number() throws Exception {
assertThat(solution(1234567890),
is("one billion two hundred thirty four million five hundred sixty seven thousand eight hundred ninety"));
}
ULocale locale = new ULocale(Locale.US); //us english
Double d = Double.parseDouble(90);
NumberFormat formatter = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);
String result = formatter.format(d);
public class TranslateNumberToWord {
/**
* Translate
*
* @param ctryCd
* @param lang
* @param reqStr
* @param fractionUnitName
* @return
*/
public static String translate(String ctryCd, String lang, String reqStr, String fractionUnitName) {
StringBuffer result = new StringBuffer();
Locale locale = new Locale(lang, ctryCd);
Currency crncy = Currency.getInstance(locale);
String inputArr[] = StringUtils.split(new BigDecimal(reqStr).abs().toPlainString(), ".");
RuleBasedNumberFormat rule = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);
int i = 0;
for (String input : inputArr) {
CurrencyAmount crncyAmt = new CurrencyAmount(new BigDecimal(input), crncy);
if (i++ == 0) {
result.append(rule.format(crncyAmt)).append(" " + crncy.getDisplayName() + " and ");
} else {
result.append(rule.format(crncyAmt)).append(" " + fractionUnitName + " ");
}
}
return result.toString();
}
public static void main(String[] args) {
String ctryCd = "US";
String lang = "en";
String input = "95.17";
String result = translate(ctryCd, lang, input, "Cents");
System.out.println("Input: " + input + " result: " + result);
}}
测试了相当大的数量和产量将是
Input: 95.17 result: ninety-five US Dollar and seventeen Cents
Input: 999999999999999999.99 result: nine hundred ninety-nine quadrillion nine hundred ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine US Dollar and ninety-nine Cents
package com.kegeesoft;
/**
* @author Chandana Gamage +94 710 980 120
* @author maheshgamage375@gmail.com
* @author KeGee Software Solutions
*/
import java.math.BigDecimal;
import java.math.BigInteger;
public class Converter {
private final BigInteger zero = new BigInteger("0");
private final BigInteger scale[] = new BigInteger[33];
private final String scaleName[] = {" Duotrigintillion"," Untrigintillion"," Trigintillion",
" Nonvigintillion"," Octovigintillion"," Septvigintillion",
" Sexvigintillion"," Quinvigintillion"," Quattuorvigintillion",
" Trevigintillion"," Duovigintillion"," Unvigintillion",
" Vigintillion"," Novemdecillion"," Octodecillion",
" Septemdecillion"," Sexdecillion"," Quindecillion",
" Quattuordecillion "," Tredecillion"," Duodecillion",
" Undecillion"," Decillion"," Nonillion"," Octillion",
" Septillion"," Sextillion"," Quintillion"," Quadrillion",
" Trillion"," Billion"," Million"," Thousand"};
private final String ones[] = {""," One"," Two"," Three"," Four"," Five"," Six"," Seven"," Eight"," Nine",
" Ten"," Eleven"," Twelve"," Thirteen"," Fourteen"," Fifteen"," Sixteen",
" Seventeen"," Eighteen"," Nineteen"};
private final String tens[] = {"",""," Twenty"," Thirty"," Forty"," Fifty"," Sixty"," Seventy"," Eighty"," Ninety"};
private int index = 0;
private String shortValueInWords = "";
private String output = "";
private String decimalInWords = "";
private String valueInWords;
public String setValue(BigInteger value) throws Exception{
return this.bigValueInWords(value);
}
public String setValue(BigDecimal value) throws Exception{
int indexOfDecimalPoint = (value.toString()).indexOf(".");
// Split and pass interger value of given decimal value to constructor
String tempIntValue = (value.toString()).substring(0, indexOfDecimalPoint);
BigInteger intValue = new BigInteger(tempIntValue);
// Split and pass decimal value of given decimal value to constructor
String tempDeciValue = (value.toString()).substring(indexOfDecimalPoint+1, value.toString().length());
BigInteger deciValue = new BigInteger(tempDeciValue);
this.bigValueInWords(intValue);
this.decimalValueInWords(deciValue);
return null;
}
public String setValue(BigDecimal value, String currencyName, String centsName) throws Exception{
int indexOfDecimalPoint = (value.toString()).indexOf(".");
// Split and pass interger value of given decimal value to constructor
String tempIntValue = (value.toString()).substring(0, indexOfDecimalPoint);
BigInteger intValue = new BigInteger(tempIntValue);
// Split and pass decimal value of given decimal value to constructor
String tempDeciValue = (value.toString()).substring(indexOfDecimalPoint+1, value.toString().length());
@SuppressWarnings("UnusedAssignment")
BigInteger deciValue = null;
// Concatenate "0" if decimal value has only single digit
if(tempDeciValue.length() == 1){
deciValue = new BigInteger(tempDeciValue.concat("0"));
}else{
deciValue = new BigInteger(tempDeciValue);
}
this.output = currencyName+" ";
this.bigValueInWords(intValue);
this.centsValueInWords(deciValue, centsName);
return null;
}
private String bigValueInWords(BigInteger value) throws Exception{
// Build scale array
int exponent = 99;
for (int i = 0; i < scale.length; i++) {
scale[i] = new BigInteger("10").pow(exponent);
exponent = exponent - 3;
}
/* Idntify whether given value is a minus value or not
if == yes then pass value without minus sign
and pass Minus word to output
*/
if(value.compareTo(zero) == -1){
value = new BigInteger(value.toString().substring(1,value.toString().length()));
output += "Minus ";
}
// Get value in words of big numbers (duotrigintillions to thousands)
for (int i=0; i < scale.length; i++) {
if((value.divide(scale[i])).compareTo(zero)==1){
this.index = (int)(value.divide(scale[i])).intValue();
output += shortValueInWords(this.index) + scaleName[i];
value = value.mod(scale[i]);
}
}
// Get value in words of short numbers (hundreds, tens and ones)
output += shortValueInWords((int)(value.intValue()));
// Get rid of any space at the beginning of output and return value in words
return this.valueInWords = output.replaceFirst("\\s", "");
}
private String shortValueInWords(int shortValue) throws Exception{
// Get hundreds
if(String.valueOf(shortValue).length()==3){
shortValueInWords = ones[shortValue / 100]+" Hundred"+shortValueInWords(shortValue % 100);
}
// Get tens
if(String.valueOf(shortValue).length()== 2 && shortValue >= 20){
if((shortValue / 10)>=2 && (shortValue % 10)>=0){
shortValueInWords = tens[shortValue / 10] + ones[shortValue % 10];
}
}
// Get tens between 10 and 20
if(String.valueOf(shortValue).length()== 2 && shortValue >= 10 && shortValue < 20){
shortValueInWords = ones[shortValue];
}
// Get ones
if(String.valueOf(shortValue).length()==1){
shortValueInWords = ones[shortValue];
}
return this.shortValueInWords;
}
private String decimalValueInWords(BigInteger decimalValue) throws Exception{
decimalInWords = " Point";
// Get decimals in point form (0.563 = zero point five six three)
for(int i=0; i < (decimalValue.toString().length()); i++){
decimalInWords += ones[Integer.parseInt(String.valueOf(decimalValue.toString().charAt(i)))];
}
return this.decimalInWords;
}
private String centsValueInWords(BigInteger decimalValue, String centsName) throws Exception{
decimalInWords = " and"+" "+centsName;
// Get cents in words (5.52 = five and cents fifty two)
if(decimalValue.intValue() == 0){
decimalInWords += shortValueInWords(decimalValue.intValue())+" Zero only";
}else{
decimalInWords += shortValueInWords(decimalValue.intValue())+" only";
}
return this.decimalInWords;
}
public String getValueInWords(){
return this.valueInWords + decimalInWords;
}
public static void main(String args[]){
Converter c1 = new Converter();
Converter c2 = new Converter();
Converter c3 = new Converter();
Converter c4 = new Converter();
try{
// Get integer value in words
c1.setValue(new BigInteger("15634886"));
System.out.println(c1.getValueInWords());
// Get minus integer value in words
c2.setValue(new BigInteger("-15634886"));
System.out.println(c2.getValueInWords());
// Get decimal value in words
c3.setValue(new BigDecimal("358621.56895"));
System.out.println(c3.getValueInWords());
// Get currency value in words
c4.setValue(new BigDecimal("358621.56"),"Dollar","Cents");
System.out.println(c4.getValueInWords());
}catch(Exception e){
e.printStackTrace();
}
}
}
package yourpackage;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Currency {
public static String convertToWords(BigDecimal num) {
return convertToWords(num.toString());
}
public static String convertToWords(String num) {
BigDecimal bd = new BigDecimal(num);
long number = bd.longValue();
long no = bd.longValue();
int decimal = (int) (bd.remainder(BigDecimal.ONE).doubleValue() * 100);
int digits_length = String.valueOf(no).length();
int i = 0;
ArrayList<String> str = new ArrayList<>();
HashMap<Integer, String> words = new HashMap<>();
words.put(0, "");
words.put(1, "One");
words.put(2, "Two");
words.put(3, "Three");
words.put(4, "Four");
words.put(5, "Five");
words.put(6, "Six");
words.put(7, "Seven");
words.put(8, "Eight");
words.put(9, "Nine");
words.put(10, "Ten");
words.put(11, "Eleven");
words.put(12, "Twelve");
words.put(13, "Thirteen");
words.put(14, "Fourteen");
words.put(15, "Fifteen");
words.put(16, "Sixteen");
words.put(17, "Seventeen");
words.put(18, "Eighteen");
words.put(19, "Nineteen");
words.put(20, "Twenty");
words.put(30, "Thirty");
words.put(40, "Forty");
words.put(50, "Fifty");
words.put(60, "Sixty");
words.put(70, "Seventy");
words.put(80, "Eighty");
words.put(90, "Ninety");
String digits[] = { "", "Hundred", "Thousand", "Lakh", "Crore" };
while (i < digits_length) {
int divider = (i == 2) ? 10 : 100;
number = no % divider;
no = no / divider;
i += divider == 10 ? 1 : 2;
if (number > 0) {
int counter = str.size();
String plural = (counter > 0 && number > 9) ? "s" : "";
String tmp = (number < 21) ? words.get(Integer.valueOf((int) number)) + " " + digits[counter] + plural
: words.get(Integer.valueOf((int) Math.floor(number / 10) * 10)) + " "
+ words.get(Integer.valueOf((int) (number % 10))) + " " + digits[counter] + plural;
str.add(tmp);
} else {
str.add("");
}
}
Collections.reverse(str);
String Rupees = String.join(" ", str).trim();
String paise = (decimal) > 0
? " And " + words.get(Integer.valueOf((int) (decimal - decimal % 10))) + " "
+ words.get(Integer.valueOf((int) (decimal % 10))) + " Paise "
: "";
return "Rupees " + Rupees + paise + " Only";
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("56721351 = " + Currency.convertToWords(new BigDecimal(56721351)));
System.out.println("76521351.61 = " + Currency.convertToWords("76521351.61"));
}
}
当您为56721351(作为大十进制)和76521351.61(作为字符串)运行此程序时,输出为
56721351 = Rupees Five Crore Sixty Seven Lakhs Twenty One Thousands Three Hundred Fifty One Only
76521351.61 = Rupees Seven Crore Sixty Five Lakhs Twenty One Thousands Three Hundred Fifty One And Sixty One Paise Only