Weekly profit per symbol - mql4

I have created a function to calculate my weekly profit and loss. It worked as per below and I would to break it down to have the only per symbols/pairs. I have been stucked on this aggregation. Any hints are appreciated.
string WeeklyProfit()
{
string msg_WeeklyProfit="";
int i,hstTotal=OrdersHistoryTotal();
double profit;
datetime starttime = iTime(Symbol(), PERIOD_W1, 0);
for(i=0;i<hstTotal;i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==TRUE)
{
if(OrderOpenTime() >= starttime)
{
profit += OrderProfit() + OrderSwap() + OrderCommission();
}
}
msg_WeeklyProfit=profit+ " "+ AccountCurrency();
}
return(msg_WeeklyProfit);
I tried to create a symbol array but that wasn’t successful. I’m stucked on the total weekly.

Here a solution if anyone needs it. But I'm still not able to have the summary per symbol. This display the impact of each trade. Letme know if you have any idea on how instead of having results as
EURUSD 1 EUR
EURUSD 2 EUR
Total: 2 EUR
I 'm missing on how to get to:
EURUSD 2 EUR
Total: 2 EUR
#include <Arrays\ArrayString.mqh>
string WeeklyProfit()
{
string msg_WeeklyProfit="";
int i,j,OrderCount,hstTotal=OrdersHistoryTotal();
double profit,profitb,profittotal;
string profitmsg="";
CArrayString *result = new CArrayString();
datetime starttime = iTime(Symbol(), PERIOD_W1, 0);
datetime starttime2 = TimeCurrent()-(7*60*60);
Print(starttime);
Print(starttime2);
for(i=0;i<hstTotal;i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==TRUE)
{
if(OrderOpenTime() >= starttime)
{
const string symbol=OrderSymbol();
if(result.Search(symbol)!=-1)
{
Print("symbol exist");
}
else
{
result.Add(symbol);
result.Sort();
Print(symbol);
}
for(j=0;j<result.Total();j++)
{
if (OrderSymbol()==result.At(j))
{
profit+=OrderProfit()+OrderSwap()+OrderCommission();
profitmsg+=symbol+ " " + DoubleToStr(profit,2) + " " + AccountCurrency()+"\n";
}
}
OrderCount++;
profittotal+=OrderProfit()+OrderSwap()+OrderCommission();
Print("profit"+ profit);
}
}
}
msg_WeeklyProfit= profitmsg +
"\n==============\n" +
"Since " + TimeToStr(starttime,TIME_DATE) + " Total: " + DoubleToStr(profittotal,2)+ AccountCurrency()+
"\n==============\n" +
OrderCount + " Trades" + " (avg: " + DoubleToStr(profittotal/OrderCount,2) + AccountCurrency()+ ") ";
if (profittotal>=0)
{
msg_WeeklyProfit += "\n"+ EMOJI_GREENCIRCLE;
}
else
{
msg_WeeklyProfit += "\n"+EMOJI_REDCIRCLE;
};
delete result;
return(msg_WeeklyProfit);
}

Another iteration and this time i'm able to have the summary but the profit is incremental instead of being per symbol.
EURUSD 1 EUR
EURGBP 2 EUR
total: 2 EUR
what am i missing on the profit approach ?
string WeeklyProfit()
{
string msg_WeeklyProfit="";
int i,j,k,OrderCount,hstTotal=OrdersHistoryTotal();
double profit,profitb,profittotal;
string profitmsg="";
CArrayString result = new CArrayString();
datetime starttime2 = TimeCurrent()-(6246060);
Print(hstTotal);
for(i=0;i<hstTotal;i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==TRUE)
{
if(OrderOpenTime() >= starttime2)
{
profittotal+=OrderProfit()+OrderSwap()+OrderCommission();
OrderCount++;
const string symbol=OrderSymbol();
if(result.Search(symbol)!=-1)
{
Print("symbol exist");
}
else
{
if (OrderType() == OP_SELL || OrderType() == OP_BUY)
{
result.Add(symbol);
result.Sort();
}
}
}
}
}
for(j=0;j<result.Total();j++)
{
for(k=0;k<hstTotal;k++)
{
if(OrderSelect(k,SELECT_BY_POS,MODE_HISTORY)==TRUE)
{
if(OrderOpenTime() >= starttime2)
{
if (OrderSymbol()==result[j])
{
if (OrderType() == OP_SELL || OrderType() == OP_BUY)
{
profit += OrderProfit() + OrderSwap() + OrderCommission();
}
}
}
}
}
profitmsg+=result[j]+ " " +DoubleToStr(profit,2) +" " + AccountCurrency() + "\n";
}
profittotal+=OrderProfit()+OrderSwap()+OrderCommission();
Print("profittotal "+ profittotal);
msg_WeeklyProfit= "Since " +TimeToStr(starttime2,TIME_DATE|TIME_MINUTES)+
"\n===================\n" +
profitmsg +
"===================\n" +
"Total: " + DoubleToStr(profittotal,2)+ " "+AccountCurrency()+
"\n"+ OrderCount + " Trades" + " (avg: " + DoubleToStr(profittotal/OrderCount,2) + AccountCurrency()+ ") ";
if (profittotal>=0)
{
msg_WeeklyProfit += "\n"+ EMOJI_GREENCIRCLE;
}
else
{
msg_WeeklyProfit += "\n"+EMOJI_REDCIRCLE;
};
delete result;
return(msg_WeeklyProfit);
}

Related

How to remove decimal point if the number more than "10" in swift

How to remove decimal point value if the number is more than 10.0. Below is the code what i have tried. At below code i am getting the value and i put the condition that if value is less than 1km then show number in meter, if value is more than 1 then show the number in km and if the value is greater than 10.0 then i am not able to remove the decimal point
let resultDelivery = String(format: "%.1f", Obj.distance)// Here getting value from api either i get 0.5 or 6.5 or 11.5
if (resultDelivery.starts(with: "0")){
let resultDelivery2 = String(format: "%.f", Obj.distance/1 * 1000)
cell.lblDeliverykm?.text = resultDelivery2.description + " " + "m".Localized() + " " + "" // result is 900 m
}
else if (resultDelivery.starts(with: "10.0")){
let resultDelivery2 = String(format: "%.0f", Obj.distance)
cell.lblDeliverykm?.text = resultDelivery2.description + " " + "km".Localized() + " " + "" // couldn’t able to remove decimal point
}
else {
cell.lblDeliverykm?.text = resultDelivery.description + " " + "km".Localized() + " " + "" // result is 8.6 km
}
Ah the joys of C-style formatting strings.
I present this as an alternative approach:
extension String.StringInterpolation
{
public mutating func appendInterpolation<F: BinaryFloatingPoint>(distance: F)
{
if distance < 1 {
appendLiteral("\(Int(distance * 1000))m")
}
else if distance >= 10 {
appendLiteral("\(Int(distance))km")
}
else
{
let d = (distance * 10).rounded(.toNearestOrEven) / 10
appendLiteral("\(d)km")
}
}
}
print("\(distance: 0.1)")
print("\(distance: 1)")
print("\(distance: 10)")
print("\(distance: 100)")
The output is
100m
1.0km
10km
100km
This will accept Double, Float, Float80, Float16 and any other type conforming to BinaryFloatingPoint.
If you want localizable formats, look into NumberFormatter.
[EDIT] as noted by #flanker in comments, LengthFormatter with its method, string(from: String, unit: LengthFormatter.Unit) -> String would be the way to go rather than NumberFormatter

Cannot resolve method error when trying to reproduce the code

I know it's been a while since this issue was resolved ( Simple calculator in java - using boolean to ask if user wants to continue ), but I wanted to recreate this, and when I tried to run it, I got error for all mathematical operators (add, minus, multiply or divide). Error says: "Cannot resolve method 'add'/'minus'/'multiply'/'divide'"
Maybe it would be easier if I add the actual code:
import javax.swing.JOptionPane;
public class Calculator {
public static void main(String[] args) {
double numberOne;
double numberTwo;
double result;
String number1;
String number2;
String input;
boolean useCalculator = false;
while (!useCalculator) {
number1 = JOptionPane.showInputDialog(null, "This is a calculator\nEnter first number");
numberOne = Double.parseDouble(number1);
input = JOptionPane.showInputDialog(null, "Choose from the following options:\n+\n-\n*\n/");
while (input == null || !(input.equals("+") || input.equals("*") || input.equals("/") || input.equals("-")))
input = JOptionPane.showInputDialog(null, "Thank you! What would you like to do?\nPlease choose from the following options:\n+\n-\n*\n/");
{
input = JOptionPane.showInputDialog(null, "The operator" + input + "is invalid. Please choose a correct one");
}
number2 = JOptionPane.showInputDialog(null, "Enter second number");
numberTwo = Double.parseDouble(number2);
if (input != null && input.equals("+")) {
add(numberOne, numberTwo);
result = add(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("-")) {
minus(numberOne, numberTwo);
result = minus(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("*")) {
multiply(numberOne, numberTwo);
result = multiply(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("/")) {
divide(numberOne, numberTwo);
result = divide(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
}
}
System.out.println("End of program.");
}
}
Any thoughts on how to fix this and run it without those errors?
Thanks in advance :)
It looks like GUI was running in the background, so when I minimized window, I was able to see the calculator and to run it normally.
Message that was displayed in console was reminder about old JDK, so everything is fine now.

Invalid Ticket when closing orders

I'm trying to close all opened orders, they are all MarketOrders not PendingOrders and have SL and TP set to 0 so they shouldn't close themselves (they are still opened in Terminal). I am storing tickets in the array so my loop looks like:
for(int i = 0; i < trades.size(); ++i) OrderClose(tickets[i], lots[i], Bid, Slippage);
yet I'm still receiving "INVALID TICKET" error, can you tell me why?
It doesn't happen always, its like some orders are closed and some throw Invalid Ticket.
I didn't notice this behavior with only 1 order so I'm assuming it occurs only when there are more of them.
Code:
template < typename T >
struct vector {
vector() {}
vector(int arraySize) {
if (arraySize < 0) { arraySize *= -1; }
ArrayResize(m_data, arraySize);
}
vector(vector & rhs) {
if (size() < rhs.size()) { ArrayResize(m_data, rhs.size()); }
for(uint i = 0; i < size(); ++i) { m_data[i] = rhs.m_data[i]; }
}
vector operator=(vector & rhs) {
if (size() < rhs.size()) { ArrayResize(m_data, rhs.size()); }
for(uint i = 0; i < size(); ++i) { m_data[i] = rhs.m_data[i]; }
return this;
}
T operator[](uint index) { return m_data[index]; }
void push_back( T value ) {
ArrayResize(m_data, ArraySize(m_data) + 1);
m_data[ ArraySize(m_data) - 1 ] = value;
}
uint size() { return ArraySize(m_data); }
void resize(uint newSize) { ArrayResize(m_data, newSize); }
void erase() {
ZeroMemory(m_data);
ArrayResize(m_data, 0);
}
void assign(uint index, T value) {
m_data[index] = value;
}
private:
T m_data[];
};
string Buy(double lots) {
string alertString = "";
int __ticket;
if ( (__ticket = OrderSend (Symbol(), OP_BUY, lots, Ask, Slippage, 0, 0, NULL, m_magic)) != -1 )
{
m_buyTicket.push_back( __ticket );
m_buyLots.push_back( lots );
m_buyPrice.push_back( Ask );
m_buyAccel.push_back( lots / Lots );
m_buyPos.push_back( 0 );
alertString = "Buy function call." +
"\nAsk\t= " + (string)Round(Ask) +
"\nBid\t= " + (string)Round(Bid) +
"\nLots\t= " + (string)Round(lots) +
"\nSpread\t= " + (string)m_spread +
"\nID\t= " + (string)CountAll();
}
else {
int _error = GetLastError();
alertString = "Error " + (string)_error + "\n" + TranslateError( _error );
}
return alertString;
}
string CloseAll() {
string alertString = "CloseAll function call.";
// Buy closing
for (uint i = 0; i < m_buyPrice.size(); ++i)
{
if ( OrderClose ( m_buyTicket[i], m_buyLots[i], Bid, Slippage) )
{
alertString += "\nBuy " + (string)(i+1) + " closed with profit " +
(string)Shrink ( (Bid - m_buyPrice[i]) * m_buyAccel[i] );
}
else
{
int _error = GetLastError();
alertString += "\nError " + (string)_error + "\n" + TranslateError( _error ) +
"\n(while closing Buy " + (string)(i+1) + ")";
}
}
// Sell closing
for (uint i = 0; i < m_sellPrice.size(); ++i)
{
if ( OrderClose ( m_sellTicket[i], m_sellLots[i], Ask, Slippage) )
{
alertString += "\nSell " + (string)(i+1) + " closed with profit " +
(string)Shrink ( (m_sellPrice[i] - Ask) * m_sellAccel[i] );
}
else
{
int _error = GetLastError();
alertString += "\nError " + (string)_error + "\n" + TranslateError( _error ) +
"\n(while closing Sell " + (string)(i+1) + ")";
}
}
return alertString;
}
when you close some ticket successfully, you do not remove it from the list trades, right? And it seems you should. Use your struct to clear the elements if order close is successful.
By the way, there's probably no need to reinvent the wheel, use CArrayObj as a container for your elements and delete them once order is closed.

Convering numbers to their English equivalent? [duplicate]

We currently have a crude mechanism to convert numbers to words (e.g. using a few static arrays) and based on the size of the number translating that into an english text. But we are running into issues for numbers which are huge.
10183 = Ten thousand one hundred eighty three
90 = Ninety
5888 = Five thousand eight hundred eighty eight
Is there an easy to use function in any of the math libraries which I can use for this purpose?
Here is the code, I don't think there is any method in SE.
It basically converts number to string and parses String and associates it with the weight
for example
1000
1 is treated as thousand position and 1 gets mapped to "one" and thousand because of position
This is the code from the website:
English
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
**/
}
}
Français
Quite different than the english version but french is a lot more difficult!
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
*/
}
}
You can handle "dollar and cent" conversion by calling the "convert" method two times.
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" ;
Another way to use a built-in function of your DBMS (if available).
For 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
ICU4J contains nice number-spellout support. The files with the "rules" can be easily edited, and it's no problem to add other languages (we did it e.g. for Polish and Russian).
Because you cannot have a general algorithm for every locale, no. You have to implement your own algorithm for every locale that you are supporting.
** EDIT **
Just for the heck of it, I played around until I got this class. It cannot display Long.MIN_VALUE because of bit restrictions... but I presume it could be modified and change long value types to double for decimal or even bigger numbers It can display any numbers up to 66 digits and 26 decimals using a string representation of the number. You may add more ScaleUnit for more decimals...
/**
* 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()));
}
}
and a sample output (for the random big number generator)
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
I think that this solution is not the best, since it works only for int, but i think it's great for a beginner.
public class NumberWordConverter {
public static final String[] units = {
"", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
public static final String[] tens = {
"", // 0
"", // 1
"twenty", // 2
"thirty", // 3
"forty", // 4
"fifty", // 5
"sixty", // 6
"seventy", // 7
"eighty", // 8
"ninety" // 9
};
public static String convert(final int n) {
if (n < 0) {
return "minus " + convert(-n);
}
if (n < 20) {
return units[n];
}
if (n < 100) {
return tens[n / 10] + ((n % 10 != 0) ? " " : "") + units[n % 10];
}
if (n < 1000) {
return units[n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
if (n < 1000000) {
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
}
if (n < 1000000000) {
return convert(n / 1000000) + " million" + ((n % 1000000 != 0) ? " " : "") + convert(n % 1000000);
}
return convert(n / 1000000000) + " billion" + ((n % 1000000000 != 0) ? " " : "") + convert(n % 1000000000);
}
public static void main(final String[] args) {
final Random generator = new Random();
int n;
for (int i = 0; i < 20; i++) {
n = generator.nextInt(Integer.MAX_VALUE);
System.out.printf("%10d = '%s'%n", n, convert(n));
}
n = 1000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 2000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 10000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 11000;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = 999999999;
System.out.printf("%10d = '%s'%n", n, convert(n));
n = Integer.MAX_VALUE;
System.out.printf("%10d = '%s'%n", n, convert(n));
}
}
The test creates 20 random numbers up to Integer.MAX_VALUE and than some that know to be problematic, because of 0, 10, etc.. Output:
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'
Hope it helps :)
package it.tommasoresti.facebook;
class NumbersToWords {
private static final String ZERO = "zero";
private static String[] oneToNine = {
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
};
private static String[] tenToNinteen = {
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
private static String[] dozens = {
"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
public static String solution(int number) {
if(number == 0)
return ZERO;
return generate(number).trim();
}
public static String generate(int number) {
if(number >= 1000000000) {
return generate(number / 1000000000) + " billion " + generate(number % 1000000000);
}
else if(number >= 1000000) {
return generate(number / 1000000) + " million " + generate(number % 1000000);
}
else if(number >= 1000) {
return generate(number / 1000) + " thousand " + generate(number % 1000);
}
else if(number >= 100) {
return generate(number / 100) + " hundred " + generate(number % 100);
}
return generate1To99(number);
}
private static String generate1To99(int number) {
if (number == 0)
return "";
if (number <= 9)
return oneToNine[number - 1];
else if (number <= 19)
return tenToNinteen[number % 10];
else {
return dozens[number / 10 - 1] + " " + generate1To99(number % 10);
}
}
}
Test
#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"));
}
/**
This Program will display the given number in words from 0 to 999999999
#author Manoj Kumar Dunna
Mail Id : manojdunna#gmail.com
**/
import java.util.Scanner;
class NumberToString
{
public enum hundreds {OneHundred, TwoHundred, ThreeHundred, FourHundred, FiveHundred, SixHundred, SevenHundred, EightHundred, NineHundred}
public enum tens {Twenty, Thirty, Forty, Fifty, Sixty, Seventy, Eighty, Ninety}
public enum ones {One, Two, Three, Four, Five, Six, Seven, Eight, Nine}
public enum denom {Thousand, Lakhs, Crores}
public enum splNums { Ten, Eleven, Twelve, Thirteen, Fourteen, Fifteen, Sixteen, Seventeen, Eighteen, Nineteen}
public static String text = "";
public static void main(String[] args)
{
System.out.println("Enter Number to convert into words");
Scanner sc = new Scanner(System.in);
long num = sc.nextInt();
int rem = 0;
int i = 0;
while(num > 0)
{
if(i == 0){
rem = (int) (num % 1000);
printText(rem);
num = num / 1000;
i++;
}
else if(num > 0)
{
rem = (int) (num % 100);
if(rem > 0)
text = denom.values()[i - 1]+ " " + text;
printText(rem);
num = num / 100;
i++;
}
}
if(i > 0)
System.out.println(text);
else
System.out.println("Zero");
}
public static void printText(int num)
{
if(!(num > 9 && num < 19))
{
if(num % 10 > 0)
getOnes(num % 10);
num = num / 10;
if(num % 10 > 0)
getTens(num % 10);
num = num / 10;
if(num > 0)
getHundreds(num);
}
else
{
getSplNums(num % 10);
}
}
public static void getSplNums(int num)
{
text = splNums.values()[num]+ " " + text;
}
public static void getHundreds(int num)
{
text = hundreds.values()[num - 1]+ " " + text;
}
public static void getTens(int num)
{
text = tens.values()[num - 2]+ " " + text;
}
public static void getOnes(int num)
{
text = ones.values()[num - 1]+ " " + text;
}
}
Take a look at Tradukisto. It's a Java library I've written which does the job.
In this post i have just update Yanick Rochon's code. I have make it workable with lower version of java 1.6 and i was getting the output for 1.00 = one and hundredth. So i have update the code. New i get the output for 1.00 = one and zero hundredth.
I don't not what should i do. Add a new answer or edit that post. As the answer is highly ranked so i have made a new post with updating the code. I have just change this two things have mention above.
/**
* 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()));
}
}
The output is
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
/* this program will display number in words
for eg. if you enter 101,it will show "ONE HUNDRED AND ONE"*/
import java.util.*;
public class NumToWords {
String string;
String st1[] = { "", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", };
String st2[] = { "hundred", "thousand", "lakh", "crore" };
String st3[] = { "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "ninteen", };
String st4[] = { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy",
"eighty", "ninety" };
public String convert(int number) {
int n = 1;
int word;
string = "";
while (number != 0) {
switch (n) {
case 1:
word = number % 100;
pass(word);
if (number > 100 && number % 100 != 0) {
show("and ");
//System.out.print("ankit");
}
number /= 100;
break;
case 2:
word = number % 10;
if (word != 0) {
show(" ");
show(st2[0]);
show(" ");
pass(word);
}
number /= 10;
break;
case 3:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[1]);
show(" ");
pass(word);
}
number /= 100;
break;
case 4:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[2]);
show(" ");
pass(word);
}
number /= 100;
break;
case 5:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[3]);
show(" ");
pass(word);
}
number /= 100;
break;
}
n++;
}
return string;
}
public void pass(int number) {
int word, q;
if (number < 10) {
show(st1[number]);
}
if (number > 9 && number < 20) {
show(st3[number - 10]);
}
if (number > 19) {
word = number % 10;
if (word == 0) {
q = number / 10;
show(st4[q - 2]);
} else {
q = number / 10;
show(st1[word]);
show(" ");
show(st4[q - 2]);
}
}
}
public void show(String s) {
String st;
st = string;
string = s;
string += st;
}
public static void main(String[] args) {
NumToWords w = new NumToWords();
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
int num = input.nextInt();
String inwords = w.convert(num);
System.out.println(inwords);
}
}
You can use ICU4J, Just need to add POM entry and code is below for any Number, Country and Language.
POM Entry
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>64.2</version>
</dependency>
Code is
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);
}}
Tested with quite a big number and output would be
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
I think this may help you...programme is very simple and works fine
import java.util.*;
public class NumberToWord
{
public void pw(int n, String ch)
{
String one[] = {
" ", " one", " two", " three", " four", " five", " six", " seven",
" eight", " Nine", " ten", " eleven", " twelve", " thirteen",
" fourteen", "fifteen", " sixteen", " seventeen", " eighteen",
" nineteen" };
String ten[] = { " ", " ", " twenty", " thirty", " forty", " fifty",
" sixty", "seventy", " eighty", " ninety" };
if (n > 19) {
System.out.print(ten[n / 10] + " " + one[n % 10]);
} else {
System.out.print(one[n]);
}
if (n > 0)
System.out.print(ch);
}
public static void main(String[] args)
{
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer number: ");
n = s.nextInt();
if (n <= 0)
System.out.print("Enter numbers greater than 0");
else
{
NumberToWord a = new NumberToWord();
System.out.print("After conversion number in words is :");
a.pw((n / 1000000000), " Hundred");
a.pw((n / 10000000) % 100, " crore");
a.pw(((n / 100000) % 100), " lakh");
a.pw(((n / 1000) % 100), " thousand");
a.pw(((n / 100) % 10), " hundred");
a.pw((n % 100), " ");
}
}
}
You can use RuleBasedNumberFormat. for example result will give you 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);
It supports a wide range of languages.
Here is a very simple class NumberInWords.java that can have the job done very easily:
String numberInWords = NumberInWords.convertNumberToWords(27546); //twenty seven thousand and five hundred forty six
It's important to know that this class is only capable of converting int datatype.
import java.util.*;
public class NumberToWord {
public void numberToword(int n, String ch) {
String one[] = {" ", " one", " two", " three", " four", " five", " six", " seven", " eight", " Nine", " ten", " eleven", " twelve", " thirteen", " fourteen", "fifteen", " sixteen", " seventeen", " eighteen", " nineteen"
};
String ten[] = {" ", " ", " twenty", " thirty", " forty", " fifty", " sixty", "seventy", " eighty", " ninety"};
if (n > 19) {
System.out.print(ten[n / 10] + " " + one[n % 10]);
} else {
System.out.print(one[n]);
}
if (n > 0) {
System.out.print(ch);
}
}
public static void main(String[] args) {
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer number: ");
n = s.nextInt();
if (n <= 0) {
System.out.print("Enter numbers greater than 0");
} else {
NumberToWord a = new NumberToWord();
System.out.print("After conversion number in words is :");
a.numberToword((n / 1000000000), " Hundred");
a.numberToword((n / 10000000) % 100, " crore");
a.numberToword(((n / 100000) % 100), " lakh");
a.numberToword(((n / 1000) % 100), " thousand");
a.numberToword(((n / 100) % 10), " hundred");
a.numberToword((n % 100), " ");
}
}
}
this might help
public String numberToWords(long number) {
if (number == 0) {
return "zero";
}
if (number < 0) {
return "minus " + numberToWords(Math.abs(number));
}
String words = "";
if ((number / 10000000) > 0) {
words += numberToWords(number / 10000000) + " Crore ";
number %= 10000000;
}
if ((number / 100000) > 0) {
words += numberToWords(number / 100000) + " Lakh ";
number %= 100000;
}
if ((number / 1000) > 0) {
words += numberToWords(number / 1000) + " Thousand ";
number %= 1000;
}
if ((number / 100) > 0) {
words += numberToWords(number / 100) + " Hundred ";
number %= 100;
}
if (number > 0) {
if (!words.equals("")) {
words += "and ";
}
if (number < 20) {
words += number;
} else {
words += (number);
if ((number % 10) > 0) {
words += "-" + (number % 10);
}
}
}
return words;
}
You probably don't need this any more, but I recently wrote a java class to do this. Apparently Yanick Rochon did something similar. It will convert numbers up to 999 Novemdecillion (999*10^60). It could do more if I knew what came after Novemdecillion, but I would be willing to bet it's unnecessary. Just feed the number as a string in cents. The output is also grammatically correct.
Here is a link to the Bitbucket Repo
The same accepted answer (Jigar Joshi), but now in Spanish. Feel free to change this if you find a mistake. Easier than french, but based on that though....
Spanish:
import java.text.*;
class SpanishNumberToWords {
private static final String[] tensNames = {
"",
"",
"veinte",
"treinta",
"cuarenta",
"cincuenta",
"sesenta",
"setenta",
"ochenta",
"noventa"
};
private static final String[] unitNames1 = {
"",
"un",
"dos",
"tres",
"cuatro",
"cinco",
"seis",
"siete",
"ocho",
"nueve",
"diez",
"once",
"doce",
"trece",
"catorce",
"quince",
"dieciseis",
"diecisiete",
"dieciocho",
"diecinueve",
"veinte",
"veintiun",
"veintidos",
"veintitres",
"veinticuatro",
"veinticinco",
"veintiseis",
"veintisiete",
"veintiocho",
"veintinueve",
};
private static final String[] unitNames2 = {
"",
"",
"dosc",
"tresc",
"cuatroc",
"quin",
"seisc",
"setec",
"ochoc",
"novec",
"diez"
};
private SpanishNumberToWords() {}
private static String convertZeroToHundred(int number) {
int theTens = number / 10;
int theUnit = number % 10;
String result = "";
// separator
String theSeparator = "";
if (theTens > 1) {
theSeparator = " y ";
}
// particular cases
switch (theUnit) {
case 0:
theSeparator = "";
break;
default:
}
// tens in letters
switch (theTens) {
case 0:
result = unitNames1[theUnit];
break;
case 1: case 2:
result = unitNames1[theTens*10+theUnit];
break;
default :
result = tensNames[theTens]
+ theSeparator + unitNames1[theUnit];
}
return result;
}
private static String convertLessThanOneThousand(int number) {
int theHundreds = number / 100;
int leReste = number % 100;
String sReste = convertZeroToHundred(leReste);
String result;
switch (theHundreds) {
case 0:
result = sReste;
break;
case 1 :
if (leReste > 0) {
result = "ciento " + sReste;
}
else {
result = "cien";
}
break;
default :
if (leReste > 0) {
result = unitNames2[theHundreds] + "ientos " + sReste;
}
else {
result = unitNames2[theHundreds] + "ientos";
}
}
return result;
}
public static String convert(long number) {
// 0 à 999 999 999 999
if (number == 0) { return "cero"; }
String snumber = Long.toString(number);
// pad des "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int theMilliards = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int theMillions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int theCentMiles = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int lesMille = Integer.parseInt(snumber.substring(9,12));
String tradMilliards;
switch (theMilliards) {
case 0:
tradMilliards = "";
break;
case 1 :
tradMilliards = convertLessThanOneThousand(theMilliards)
+ " mil millones ";
break;
default :
tradMilliards = convertLessThanOneThousand(theMilliards)
+ " mil millones ";
}
String resultat = tradMilliards;
String tradMillions;
switch (theMillions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(theMillions)
+ " millon ";
break;
default :
tradMillions = convertLessThanOneThousand(theMillions)
+ " millones ";
}
resultat = resultat + tradMillions;
String tradCentMille;
switch (theCentMiles) {
case 0:
tradCentMille = "";
break;
case 1 :
tradCentMille = "mil ";
break;
default :
tradCentMille = convertLessThanOneThousand(theCentMiles)
+ " mil ";
}
resultat = resultat + tradCentMille;
String tradMille;
tradMille = convertLessThanOneThousand(lesMille);
resultat = resultat + tradMille;
return resultat;
}
public static void main(String[] args) {
System.out.println("*** " + SpanishNumberToWords.convert(0));
System.out.println("*** " + SpanishNumberToWords.convert(1));
System.out.println("*** " + SpanishNumberToWords.convert(2));
System.out.println("*** " + SpanishNumberToWords.convert(3));
System.out.println("*** " + SpanishNumberToWords.convert(4));
System.out.println("*** " + SpanishNumberToWords.convert(5));
System.out.println("*** " + SpanishNumberToWords.convert(7));
System.out.println("*** " + SpanishNumberToWords.convert(12));
System.out.println("*** " + SpanishNumberToWords.convert(16));
System.out.println("*** " + SpanishNumberToWords.convert(19));
System.out.println("*** " + SpanishNumberToWords.convert(21));
System.out.println("*** " + SpanishNumberToWords.convert(24));
System.out.println("*** " + SpanishNumberToWords.convert(28));
System.out.println("*** " + SpanishNumberToWords.convert(29));
System.out.println("*** " + SpanishNumberToWords.convert(30));
System.out.println("*** " + SpanishNumberToWords.convert(31));
System.out.println("*** " + SpanishNumberToWords.convert(42));
System.out.println("*** " + SpanishNumberToWords.convert(71));
System.out.println("*** " + SpanishNumberToWords.convert(72));
System.out.println("*** " + SpanishNumberToWords.convert(80));
System.out.println("*** " + SpanishNumberToWords.convert(81));
System.out.println("*** " + SpanishNumberToWords.convert(89));
System.out.println("*** " + SpanishNumberToWords.convert(90));
System.out.println("*** " + SpanishNumberToWords.convert(91));
System.out.println("*** " + SpanishNumberToWords.convert(97));
System.out.println("*** " + SpanishNumberToWords.convert(100));
System.out.println("*** " + SpanishNumberToWords.convert(101));
System.out.println("*** " + SpanishNumberToWords.convert(110));
System.out.println("*** " + SpanishNumberToWords.convert(120));
System.out.println("*** " + SpanishNumberToWords.convert(200));
System.out.println("*** " + SpanishNumberToWords.convert(201));
System.out.println("*** " + SpanishNumberToWords.convert(232));
System.out.println("*** " + SpanishNumberToWords.convert(999));
System.out.println("*** " + SpanishNumberToWords.convert(521));
System.out.println("*** " + SpanishNumberToWords.convert(912));
System.out.println("*** " + SpanishNumberToWords.convert(999));
System.out.println("*** " + SpanishNumberToWords.convert(1000));
System.out.println("*** " + SpanishNumberToWords.convert(1001));
System.out.println("*** " + SpanishNumberToWords.convert(10000));
System.out.println("*** " + SpanishNumberToWords.convert(10001));
System.out.println("*** " + SpanishNumberToWords.convert(100000));
System.out.println("*** " + SpanishNumberToWords.convert(267578));
System.out.println("*** " + SpanishNumberToWords.convert(3000000000L));
System.out.println("*** " + SpanishNumberToWords.convert(2147483647));
/*
*** OUTPUT
*** cero
*** un
*** dos
*** tres
*** cuatro
*** cinco
*** siete
*** doce
*** dieciseis
*** diecinueve
*** veintiun
*** veinticuatro
*** veintiocho
*** veintinueve
*** treinta
*** treinta y un
*** cuarenta y dos
*** setenta y un
*** setenta y dos
*** ochenta
*** ochenta y un
*** ochenta y nueve
*** noventa
*** noventa y un
*** noventa y siete
*** cien
*** ciento un
*** ciento diez
*** ciento veinte
*** doscientos
*** doscientos un
*** doscientos treinta y dos
*** novecientos noventa y nueve
*** quinientos veintiun
*** novecientos doce
*** novecientos noventa y nueve
*** mil
*** mil un
*** diez mil
*** diez mil un
*** cien mil
*** doscientos sesenta y siete mil quinientos setenta y ocho
*** tres mil millones
*** dos mil millones ciento cuarenta y siete millones cuatrocientos ochenta y tres mil seiscientos cuarenta y siete
*/
}
class NumberToWord {
private static Map<Integer, String> numbers = new HashMap<Integer, String>();
private static Set<Integer> numberSet = new TreeSet<Integer>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
static {
init();
numberSet.addAll(numbers.keySet());
}
public static void main(String[] args) {
System.out.println(getNumberInWord(1898765));
}
/*
* convert positive numbers in word format number > 0 only
*/
static String getNumberInWord(int number) {
StringBuilder word = new StringBuilder();
for (Integer n : numberSet) {
if (number > 0 && number >= n) {
int div = number / n;
String strNum = numbers.get(div);
if (strNum == null) {
word.append(getNumberInWord(div));
}
// for less than 100, we don't need to say 1
if (strNum != null && (div > 1 || n > 100))
word.append(strNum + " ");
word.append(numbers.get(n) + " ");
number = number % n;
}
}
return word.toString();
}
static void init() {
numbers.put(0, "Zero");
numbers.put(1, "One");
numbers.put(2, "Two");
numbers.put(3, "Three");
numbers.put(4, "Four");
numbers.put(5, "Five");
numbers.put(6, "Six");
numbers.put(7, "Seven");
numbers.put(8, "Eight");
numbers.put(9, "Nine");
numbers.put(10, "Ten");
numbers.put(11, "Eleven");
numbers.put(12, "Twelve");
numbers.put(13, "Thirteen");
numbers.put(14, "Fourteen");
numbers.put(15, "Fifteen");
numbers.put(16, "Sixteen");
numbers.put(17, "Seventeen");
numbers.put(18, "Eighteeen");
numbers.put(19, "Nineteen");
numbers.put(20, "Twenty");
numbers.put(30, "Thirty");
numbers.put(40, "Forty");
numbers.put(50, "Fifty");
numbers.put(60, "Sixty");
numbers.put(70, "Seventy");
numbers.put(80, "Eighty");
numbers.put(90, "Ninty");
numbers.put(100, "Hundred");
numbers.put(1000, "Thousand");
numbers.put(1000000, "Million");
numbers.put(100000000, "Billion");
}
}
I've developed a Java component to convert given number into words. All you've to do is - just copy the whole class from Java program to convert numbers to words and paste it in your project.
Just invoke it like below
Words w = Words.getInstance(1234567);
System.out.println(w.getNumberInWords());
My program supports up to 10 million. If you want, you can still extend this. Just below the example output
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
Thanks
Santhosh
Intuitive solution
1: Build a sorted matrix of [value - word] type
2: Find the closest value from matrix for which n/value > 0 (can use binary_search)
3: Recursively build the left and the right part of the number.
Your answer is left_part + word + right_part
class Solution {
private final Object[][] pairs = {
{1000_000_000, "Billion"}, {100_00_00, "Million"}, {1000, "Thousand"}, {100, "Hundred"},
{90, "Ninety"}, {80, "Eighty"}, {70, "Seventy"}, {60, "Sixty"},
{50, "Fifty"}, {40, "Forty"}, {30, "Thirty"}, {20, "Twenty"},
{19, "Nineteen"}, {18, "Eighteen"}, {17, "Seventeen"}, {16, "Sixteen"},
{15, "Fifteen"}, {14, "Fourteen"}, {13, "Thirteen"}, {12, "Twelve"},
{11, "Eleven"}, {10, "Ten"}, {9, "Nine"}, {8, "Eight"},
{7, "Seven"}, {6, "Six"}, {5, "Five"}, {4, "Four"},
{3, "Three"}, {2, "Two"}, {1, "One"}
};
private Object[] getPair(int num) {
int n = pairs.length;
int l = 0, r = n - 1;
int result = -1;
while (l <= r) {
int mid = (l + r) >>> 1;
int value = (Integer) pairs[mid][0];
if (value == num) {
return pairs[mid];
}
else if (num / value > 0) {
result = mid;
r = mid - 1;
}
else {
l = mid + 1;
}
}
return pairs[result];
}
public String numberToWords(int num) {
if (num == 0) {
return "Zero";
}
var pair = getPair(num);
String word = (String) pair[1];
int value = (Integer) pair[0];
var left = num >= 100 ? numberToWords(num / value) + " " : "";
var right = num % value == 0 ? "" : " " + numberToWords(num % value);
return left + word + right;
}
}
I implemented it like this
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;
}
}
and the resource file is :
0=zero
1=one
2=two
3=three
4=four
5=five
6=six
7=seven
8=eight
9=nine
10=ten
11=eleven
12=twelve
13=thirteen
14=fourteen
15fifteen
16=sixteen
17=seventeen
18=eighteen
19=nineteen
20=twenty
30=thirty
40=fourty
50=fifty
60=sixty
70=seventy
80=eighty
90=ninety
100=hundred
1000=thousand
100000=Lakh
This one is implemented till 10 lakhs only
public class NumberConverter {
private String[] singleDigit = {"", " one", " two", " three",
" four", " five"," six", " seven", " eight", " nine"};
private String[] tens = {" ten", " eleven", " twelve", " thirteen",
" fourteen", " fifteen"," sixteen", " seventeen", " eighteen", " nineteen"};
private String[] twoDigits = {"", "", " twenty", " thirty",
" forty", " fifty"," sixty", " seventy", " eighty", " ninety"};
public String convertToWords(String input) {
long number = Long.parseLong(input);
int size = input.length();
if (size <= 3) {
int num = (int) number;
return handle3Digits(num);
} else if (size > 3 && size <= 6) {
int thousand = (int)(number/1000);
int hundred = (int) (number % 1000);
String thousands = handle3Digits(thousand);
String hundreds = handle3Digits(hundred);
String word = "";
if (!thousands.isEmpty()) {
word = thousands +" thousand";
}
word += hundreds;
return word;
} else if (size > 6 && size <= 9) {
int million = (int) (number/ 1000000);
number = number % 1000000;
int thousand = (int)(number/1000);
int hundred = (int) (number % 1000);
String millions = handle3Digits(million);
String thousands = handle3Digits(thousand);
String hundreds = handle3Digits(hundred);
String word = "";
if (!millions.isEmpty()) {
word = millions +" million";
}
if (!thousands.isEmpty()) {
word += thousands +" thousand";
}
word += hundreds;
return word;
}
return "Not implemented yet.";
}
private String handle3Digits(int number) {
if (number <= 0)
return "";
String word = "";
if (number/100 > 0) {
int dividend = number/100;
word = singleDigit[dividend] + " hundred";
number = number % 100;
}
if (number/10 > 1) {
int dividend = number/10;
number = number % 10;
word += twoDigits[dividend];
} else if (number/10 == 1) {
number = number % 10;
word += tens[number];
return word;
} else {
number = number % 10;
}
if (number > 0) {
word += singleDigit[number];
}
return word;
}
}
This program can convert up to 102 digits long number. Suggestions and comments are highly appreciated.
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();
}
}
}
I tried to make the code more readable. This works for numbers within integer range
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
public class Solution2 {
static Map<Integer, String> numberMap = new HashMap<Integer, String>();
static Map<Integer, String> tensMap = new HashMap<Integer, String>();
static Map<Integer, String> exponentsMap = new HashMap<Integer, String>();
public static void main(String[] args) {
LinkedList<String> wordList = new LinkedList<String>();
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
scan.close();
exponentsMap.put(3, "thousand");
exponentsMap.put(6, "million");
exponentsMap.put(9, "billion");
tensMap.put(2, "twenty");
tensMap.put(3, "thirty");
tensMap.put(4, "forty");
tensMap.put(5, "fifty");
tensMap.put(6, "sixty");
tensMap.put(7, "seventy");
tensMap.put(8, "eighty");
tensMap.put(9, "ninety");
numberMap.put(1, "one");
numberMap.put(2, "two");
numberMap.put(3, "three");
numberMap.put(4, "four");
numberMap.put(5, "five");
numberMap.put(6, "six");
numberMap.put(7, "seven");
numberMap.put(8, "eight");
numberMap.put(9, "nine");
numberMap.put(10, "ten");
numberMap.put(11, "eleven");
numberMap.put(12, "twelve");
numberMap.put(13, "thirteen");
numberMap.put(14, "fourteen");
numberMap.put(15, "fifteen");
numberMap.put(16, "sixteen");
numberMap.put(17, "seventeen");
numberMap.put(18, "eighteen");
numberMap.put(19, "nineteen");
int temp = input;
int exponentCounter =0;
while(temp>0) {
// words from 1 to 99
addLastTwo(temp%100,wordList);
temp=temp/100;
// add hundreds before exponents
if(temp!=0) {
wordList.addFirst("hundred");
wordList.addFirst(numberMap.getOrDefault(temp%10,""));
temp = temp/10;
}
// words for exponents
if(temp!=0) {
exponentCounter+=3;
wordList.addFirst(exponentsMap.getOrDefault(exponentCounter,""));
}
}
wordList.stream().filter(word -> !word.contentEquals("")).forEach(word -> System.out.print(word + " "));
}
private static void addLastTwo(int num, LinkedList<String> wordList) {
if (num > 19) {
wordList.addFirst(numberMap.getOrDefault(num % 10,""));
wordList.addFirst(tensMap.getOrDefault(num / 10,""));
} else {
wordList.addFirst(numberMap.getOrDefault(num,""));
}
}
}
Find this code for Indian rupees and in lakhs & crores than Million and Billion. You can pass String or Bigdecimal to the method. This will give the correct output for paisa as well.
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"));
}
}
When you run this program for 56721351(as Bigdecimal) and 76521351.61(as String) the output is
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
Below java program demonstrate how to convert a number from zero to one million.
NumberToStringLiteral class :
public class NumberToStringLiteral
{
public static void main(String[] args)
{
NumberToStringLiteral numberToStringLiteral = new NumberToStringLiteral();
int number = 123456;
String stringLiteral = numberToStringLiteral.convertIntegerToStringLiteral(number);
System.out.println(stringLiteral);
}
private String convertIntegerToStringLiteral(int number)
{
if (number < 100)
return from_0_To_100(number);
if ( number >= 100 && number < 1000 )
return from_101_To_999(number);
if ( number >= 1000 && number <= 99999)
return from_1000_To_99999(number);
if (number <= 1000000)
return from_100000_and_above(number);
return Digits.OVER_ONE_MILLION.getStringLiteral();
}
private String from_0_To_100(int number)
{
if (number <= 19 )
return ZeroToNineteen.getStringLiteral(number);
String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 10) != ZeroToNineteen.ZERO.getStringLiteral() ) ?
ZeroToNineteen.getStringLiteral(number % 10) : "";
return Tens.getStringLiteralFromNumber( (number - (number % 10 )) ) + " " + LastDigit;
}
private String from_101_To_999(int number)
{
String LastDigit = ( ZeroToNineteen.getStringLiteral(number % 100) != ZeroToNineteen.ZERO.getStringLiteral() ) ?
ZeroToNineteen.getStringLiteral(number % 100) : "";
if ( (number % 100) > 19)
LastDigit = from_0_To_100(number % 100);
if (LastDigit.isBlank())
return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(0));
return ZeroToNineteen.getStringLiteral(number / 100 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
}
private String from_1000_To_99999(int number)
{
String LastDigit = (number % 1000 < 20 ) ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
if (LastDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.getStringLiteral()))
LastDigit = "";
return from_0_To_100(number / 1000 ) + Digits.getStringLiteral(getNumberOfDigit(number)) + LastDigit;
}
private String from_100000_and_above(int number)
{
if (number == 1000000)
return Digits.ONE_MILLION.getStringLiteral();
String lastThreeDigit = (number % 1000 <= 100) ? from_0_To_100(number % 1000) : from_101_To_999(number % 1000);
if (lastThreeDigit.equalsIgnoreCase(ZeroToNineteen.ZERO.toString()))
lastThreeDigit = "";
String number1 = from_101_To_999(number / 1000) + Digits.THOUSAND.getStringLiteral() + lastThreeDigit;
return String.valueOf(number1);
}
private int getNumberOfDigit(int number)
{
int count = 0;
while ( number != 0 )
{
number /= 10;
count++;
}
return count;
}
}
ZeroToNineteen enum :
public enum ZeroToNineteen
{
ZERO(0, "zero"),
ONE(1, "one"),
TWO(2, "two"),
THREE(3, "three"),
FOUR(4, "four"),
FIVE(5, "five"),
SIX(6, "six"),
SEVEN(7, "seven"),
EIGHT(8, "eight"),
NINE(9, "nine"),
TEN(10, "ten"),
ELEVEN(11, "eleven"),
TWELVE(12, "twelve"),
THIRTEEN(13, "thirteen"),
FOURTEEN(14, "fourteen"),
FIFTEEN(15, "fifteen"),
SIXTEEN(16, "sixteen"),
SEVENTEEN(17, "seventeen"),
EIGHTEEN(18, "eighteen"),
NINETEEN(19, "nineteen");
private int number;
private String stringLiteral;
public static Map<Integer, String> stringLiteralMap;
ZeroToNineteen(int number, String stringLiteral)
{
this.number = number;
this.stringLiteral = stringLiteral;
}
public int getNumber()
{
return this.number;
}
public String getStringLiteral()
{
return this.stringLiteral;
}
public static String getStringLiteral(int number)
{
if (stringLiteralMap == null)
addData();
return stringLiteralMap.get(number);
}
private static void addData()
{
stringLiteralMap = new HashMap<>();
for (ZeroToNineteen zeroToNineteen : ZeroToNineteen.values())
{
stringLiteralMap.put(zeroToNineteen.getNumber(), zeroToNineteen.getStringLiteral());
}
}
}
Tens enum :
public enum Tens
{
TEN(10, "ten"),
TWENTY(20, "twenty"),
THIRTY(30, "thirty"),
FORTY(40, "forty"),
FIFTY(50, "fifty"),
SIXTY(60, "sixty"),
SEVENTY(70, "seventy"),
EIGHTY(80, "eighty"),
NINETY(90, "ninety"),
HUNDRED(100, "one hundred");
private int number;
private String stringLiteral;
private static Map<Integer, String> stringLiteralMap;
Tens(int number, String stringLiteral)
{
this.number = number;
this.stringLiteral = stringLiteral;
}
public int getNumber()
{
return this.number;
}
public String getStringLiteral()
{
return this.stringLiteral;
}
public static String getStringLiteralFromNumber(int number)
{
if (stringLiteralMap == null)
addDataToStringLiteralMap();
return stringLiteralMap.get(number);
}
private static void addDataToStringLiteralMap()
{
stringLiteralMap = new HashMap<Integer, String>();
for (Tens tens : Tens.values())
stringLiteralMap.put(tens.getNumber(), tens.getStringLiteral());
}
}
Digits enum :
public enum Digits
{
HUNDRED(3, " hundred and "),
THOUSAND(4, " thousand "),
TEN_THOUSAND(5," thousand "),
ONLY_HUNDRED(0, " hundred" ),
ONE_MILLION(1000000, "one million"),
OVER_ONE_MILLION(1000001, "over one million");
private int digit;
private String stringLiteral;
private static Map<Integer, String> stringLiteralMap;
private Digits(int digit, String stringLiteral)
{
this.digit = digit;
this.stringLiteral = stringLiteral;
}
public int getDigit()
{
return this.digit;
}
public String getStringLiteral()
{
return this.stringLiteral;
}
public static String getStringLiteral(int number)
{
if ( stringLiteralMap == null )
addStringLiteralMap();
return stringLiteralMap.get(number);
}
private static void addStringLiteralMap()
{
stringLiteralMap = new HashMap<Integer, String>();
for ( Digits digits : Digits.values() )
stringLiteralMap.put(digits.getDigit(), digits.getStringLiteral());
}
}
Output :
one hundred and twenty three thousand four hundred and fifty six
Note: I have used all three enum for constant variables, you can also use array.
Hope this will help you, Let me know if you have any doubt in comment section.
//international number system
static String point = "point";
static String h = "hundred";
static String th = "thousand";
static String m = "million";
static String b = "billion";
static String
_0 = "",
_1 = "one",
_2 = "two",
_3 = "three",
_4 = "four",""
_5 = "five",
_6 = "six",
_7 = "seven",
_8 = "eight",
_9 = "nine";
static String
_00 = "",
_10 = "ten",
_20 = "twenty",
_30 = "thirty",
_40 = "forty",
_50 = "fifty",
_60 = "sixty",
_70 = "seventy",
_80 = "eighty",
_90 = "ninety";
static String
_11 = "eleven",
_12 = "twelve",
_13 = "thirteen",
_14 = "forteen",
_15 = "fifteen",
_16 = "sixteen",
_17 = "seventeen",
_18 = "eighteen",
_19 = "nineteen";
static String
_000 = "",
_100 = _1 + " " + h,
_200 = _2 + " " + h,
_300 = _3 + " " + h,
_400 = _4 + " " + h,
_500 = _5 + " " + h,
_600 = _6 + " " + h,
_700 = _7 + " " + h,
_800 = _8 + " " + h,
_900 = _9 + " " + h;
static String[][][] numberNames = new String[][][]{
{
{_0, _1, _2, _3, _4, _5, _6, _7, _8, _9},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90},
{_000, _100, _200, _300, _400, _500, _600, _700, _800, _900}
},
{
{_0, _1+" "+th, _2+" "+th, _3+" "+th, _4+" "+th, _5+" "+th,
_6+" "+th, _7+" "+th, _8+" "+th, _9+" "+th},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90},
{_000, _100, _200, _300, _400, _500, _600, _700, _800, _900}
},
{
{_0, _1+" "+m, _2+" "+m, _3+" "+m, _4+" "+m, _5+" "+m,
_6+" "+m, _7+" "+m, _8+" "+m, _9+" "+m},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90},
{_000, _100, _200, _300, _400, _500, _600, _700, _800, _900}
},
{
{_0, _1+" "+b, _2+" "+b, _3+" "+b, _4+" "+b, _5+" "+b,
_6+" "+b, _7+" "+b, _8+" "+b, _9+" "+b},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90},
{_000, _100, _200, _300, _400, _500, _600, _700, _800, _900}
}
};
//indian number system
static String l = "lakh";
static String c = "crore";
static String a = "arab";
static String[][][] indianNumberNames = new String[][][]{
{
{_0, _1, _2, _3, _4, _5, _6, _7, _8, _9},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90},
{_000, _100, _200, _300, _400, _500, _600, _700, _800, _900}
},
{
{_0, _1+" "+th, _2+" "+th, _3+" "+th, _4+" "+th, _5+" "+th,
_6+" "+th, _7+" "+th, _8+" "+th, _9+" "+th},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90}
},
{
{_0, _1+" "+l, _2+" "+l, _3+" "+l, _4+" "+l, _5+" "+l,
_6+" "+l, _7+" "+l, _8+" "+l, _9+" "+l},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90}
},
{
{_0, _1+" "+c, _2+" "+c, _3+" "+c, _4+" "+c, _5+" "+c,
_6+" "+c, _7+" "+c, _8+" "+c, _9+" "+c},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90}
},
{
{_0, _1+" "+a, _2+" "+a, _3+" "+a, _4+" "+a, _5+" "+a,
_6+" "+a, _7+" "+a, _8+" "+a, _9+" "+a},
{_00, _10, _20, _30, _40, _50, _60, _70, _80, _90}
}
};
//the grouping of numbers,
//such as 1 000 000 000 where each group contains 3 digits,
//or 1 00 00 00 000 for indian number system,
//where each group contains 2 digits except the first group which has 3.
//may differ from one number system to another.
static int place_difference = 3;
//current number system
static int curNumSys = INTERNATIONAL_NUMBER_SYSTEM;
public static String convertToNumberName(String number){
String[] split = number.split("\\.");
String num1, num2;
num1 = split[0];
num2 = split.length > 1 ? split[1] : "";
int place_counter = 0;
int step = 0;
Stack<String> numberNameBuilder = new Stack<>();
StringBuilder builder = new StringBuilder();
builder.append(num1);
num1 = (builder.reverse()).toString();
builder.setLength(0);
int counter = -1;
for(int i = 0; i < num1.length(); i++){
int c = Integer.parseInt(num1.charAt(i) + "");
counter++;
place_counter = counter % place_difference;
if (place_counter == 0){
step++;
//specific number system component, this is for indian number system
//find a generic approach at a later time
// if (step == 2){
// counter = 0;
// place_difference = 2;
// }
}
String name = getDataSet()[step - 1][place_counter][c];
numberNameBuilder.push(name);
}
while(numberNameBuilder.hasNext()){
builder.append(numberNameBuilder.pop() + " ");
}
String str = builder.toString();
str = refine(str);
builder.setLength(0);
builder.append(num2);
num2 = builder.reverse().toString();
builder.setLength(0);
//decimal conversion here
for(int i = 0; i < num2.length(); i++){
int c = Integer.parseInt(num2.charAt(i) + "");
numberNameBuilder.push(getDataSet()[0][0][c]);
}
while(numberNameBuilder.hasNext()){
builder.append(numberNameBuilder.pop() + " ");
}
str += point + " ";
str += builder.toString();
return str;
}
private static String refine(String str){
str = str.replace(_10 + " " + _1, _11);
str = str.replace(_10 + " " + _2, _12);
str = str.replace(_10 + " " + _3, _13);
str = str.replace(_10 + " " + _4, _14);
str = str.replace(_10 + " " + _5, _15);
str = str.replace(_10 + " " + _6, _16);
str = str.replace(_10 + " " + _7, _17);
str = str.replace(_10 + " " + _8, _18);
str = str.replace(_10 + " " + _9, _19);
return str;
}
private static String[][][] getDataSet(){
switch(curNumSys){
case INDIAN_NUMBER_SYSTEM :
return indianNumberNames;
case INTERNATIONAL_NUMBER_SYSTEM :
return numberNames;
}
return numberNames;
}
Just simply call the convertToNumberName() function and give the numbers as string,to change from international to Indian, simply uncomment the commented lines in the function mentioned above, to add more number systems, more data sets and minor tweaking in the function will be required.
The stack mentioned here is just a simple LIFO structure and with ordinary stack functions, one could use their own custom implementation of the stack here or just import from Java.
The limit can be expanded further, for example, international number system only has capacity to convert up-to 999 billions, however, the data set can be expanded further to add trillions and quadrillions and more, it can go as far as the dataset that is the 3d array in code above allows it to.
import java.util.Scanner;
public class StringToNum {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no: ");
int no=sc.nextInt();
int arrNum[]=new int[10];
int i=0;
while(no!=0)
{
arrNum[i]=no%10;
no=no/10;
i++;
}
int len=i;
int arrNum1[]=new int[len];
int j=0;
for(int k=len-1;k>=0;k--)
{
arrNum1[j]=arrNum[k];
j++;
}
StringToNum stn=new StringToNum();
String output="";
switch(len)
{
case 1:
{
output+=stn.strNum1(arrNum1[len-1]);
System.out.println("output="+output);
break;
}
case 2:
{
int no1=arrNum1[len-2]*10+arrNum1[len-1];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1);
// output=output+" "+stn.strNum1(arrNum1[len-1]);
System.out.println("output="+output);
}
else
{
arrNum1[len-2]=arrNum1[len-2]*10;
output+=stn.strNum2(arrNum1[len-2]);
output=output+" "+stn.strNum1(arrNum1[len-1]);
System.out.println("output="+output);
}
break;
}
case 3:
{
output=stn.strNum1(arrNum1[len-3])+" hundred ";
int no1=arrNum1[len-2]*10+arrNum1[len-1];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1);
}
else
{
arrNum1[len-2]=arrNum1[len-2]*10;
output+=stn.strNum2(arrNum1[len-2]);
output=output+" "+stn.strNum1(arrNum1[len-1]);
}
System.out.println("output="+output);
break;
}
case 4:
{
output=stn.strNum1(arrNum1[len-4])+" thousand ";
if(!stn.strNum1(arrNum1[len - 3]).equals(""))
{
output+=stn.strNum1(arrNum1[len-3])+" hundred ";
}
int no1=arrNum1[len-2]*10+arrNum1[len-1];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1);
}
else
{
arrNum1[len-2]=arrNum1[len-2]*10;
output+=stn.strNum2(arrNum1[len-2]);
output=output+" "+stn.strNum1(arrNum1[len-1]);
}
System.out.println("output="+output);
break;
}
case 5:
{
int no1=arrNum1[len-5]*10+arrNum1[len-4];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1)+" thousand ";
}
else
{
arrNum1[len-5]=arrNum1[len-5]*10;
output+=stn.strNum2(arrNum1[len-5]);
output=output+" "+stn.strNum1(arrNum1[len-4])+" thousand ";
}
if( !stn.strNum1(arrNum1[len - 3]).equals(""))
{
output+=stn.strNum1(arrNum1[len-3])+" hundred ";
}
no1 = arrNum1[len - 2] * 10 + arrNum1[len - 1];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1);
}
else
{
arrNum1[len-2]=arrNum1[len-2]*10;
output+=stn.strNum2(arrNum1[len-2]);
output=output+" "+stn.strNum1(arrNum1[len-1]);
}
System.out.println("output="+output);
break;
}
case 6:
{
output+=stn.strNum1(arrNum1[len-6])+" million ";
int no1=arrNum1[len-5]*10+arrNum1[len-4];
if(no1>=11 & no1<=19)
{
output+=stn.strNum2(no1)+" thousand ";
}
else
{
arrNum1[len-5]=arrNum1[len-5]*10;
output+=stn.strNum2(arrNum1[len-5]);
output=output+" "+stn.strNum1(arrNum1[len-4])+" thousand ";
}
if( !stn.strNum1(arrNum1[len - 3]).equals(""))
{
output+=stn.strNum1(arrNum1[len-3])+" hundred ";
}
no1 = arrNum1[len - 2] * 10 + arrNum1[len - 1];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1);
}
else
{
arrNum1[len-2]=arrNum1[len-2]*10;
output+=stn.strNum2(arrNum1[len-2]);
output=output+" "+stn.strNum1(arrNum1[len-1]);
}
System.out.println("output="+output);
break;
}
case 7:
{
int no1=arrNum1[len-7]*10+arrNum1[len-6];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1)+" Milloin ";
}
else
{
arrNum1[len-7]=arrNum1[len-7]*10;
output+=stn.strNum2(arrNum1[len-7]);
output=output+" "+stn.strNum1(arrNum1[len-6])+" Million ";
}
no1=arrNum1[len-5]*10+arrNum1[len-4];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1)+" Thousand ";
}
else
{
arrNum1[len-5]=arrNum1[len-5]*10;
output+=stn.strNum2(arrNum1[len-5]);
output=output+" "+stn.strNum1(arrNum1[len-4])+" Thousand ";
}
if( !stn.strNum1(arrNum1[len - 3]).equals(""))
{
output+=stn.strNum1(arrNum1[len-3])+" Hundred ";
}
no1 = arrNum1[len - 2] * 10 + arrNum1[len - 1];
if(no1>=11 & no1<=19)
{
output=stn.strNum2(no1);
}
else
{
arrNum1[len-2]=arrNum1[len-2]*10;
output+=stn.strNum2(arrNum1[len-2]);
output=output+" "+stn.strNum1(arrNum1[len-1]);
}
System.out.println("output="+output);
break;
}
}
}
String strNum1(int a)
{
String op="";
switch(a)
{
case 1:
{
op="one";
break;
}
case 2:
{
op="two";
break;
}
case 3:
{
op="three";
break;
}
case 4:
{
op="four";
break;
}
case 5:
{
op="five";
break;
}
case 6:
{
op="six";
break;
}
case 7:
{
op="seven";
break;
}
case 8:
{
op="eight";
break;
}
case 9:
{
op="nine";
break;
}
}
return op;
}
String strNum2(int a)
{
String op="";
switch(a)
{
case 10:
{
op="ten";
break;
}
case 20:
{
op="twenty";
break;
}
case 30:
{
op="thirty";
break;
}
case 40:
{
op="fourty";
break;
}
case 50:
{
op="fifty";
break;
}
case 60:
{
op="sixty";
break;
}
case 70:
{
op="seventy";
break;
}
case 80:
{
op="eighty";
break;
}
case 90:
{
op="ninty";
break;
}
case 11:
{
op="eleven";
break;
}
case 12:
{
op="twelve";
break;
}
case 13:
{
op="thirteen";
break;
}
case 14:
{
op="fourteen";
break;
}
case 15:
{
op="fifteen";
break;
}
case 16:
{
op="sixteen";
break;
}
case 17:
{
op="seventeen";
break;
}
case 18:
{
op="eighteen";
break;
}
case 19:
{
op="nineteen";
break;
}
}
return op;
}
}
/* This program will print words for a number between 0 to 99999*/
public class NumberInWords5Digits {
static int testcase1 = 93284;
public static void main(String args[]){
NumberInWords5Digits testInstance = new NumberInWords5Digits();
String result = testInstance.inWords(testcase1);
System.out.println("Result : "+result);
}
//write your code here
public String inWords(int num){
int digit = 0;
String word = "";
int temp = num;
while(temp>0)
{
if(temp%10 >= 0)
digit++;
temp = temp/10;
}
if(num == 0)
return "zero";
System.out.println(num);
if(digit == 1)
word = inTens(num, digit);
else if(digit == 2)
word = inTens(num, digit);
else if(digit == 3)
word = inHundreds(num, digit);
else if(digit == 4)
word = inThousands(num, digit);
else if(digit == 5)
word = inThousands(num, digit);
return word;
}
public String inTens(int num, int digit){
int tens = 0;
int units = 0;
if(digit == 2)
{
tens = num/10;
units = num%10;
}
String unit = "";
String ten = "";
String word = "";
if(num == 10)
{word = "ten"; return word;}
if(num == 11)
{word = "eleven"; return word;}
if(num == 12)
{word = "twelve"; return word;}
if(num == 13)
{word = "thirteen"; return word;}
if(num == 14)
{word = "fourteen"; return word;}
if(num == 15)
{word = "fifteen"; return word;}
if(num == 16)
{word = "sixteen"; return word;}
if(num == 17)
{word = "seventeen"; return word;}
if(num == 18)
{word = "eighteen"; return word;}
if(num == 19)
{word = "nineteen"; return word;}
if(units == 1 || num == 1)
unit = "one";
else if(units == 2 || num == 2)
unit = "two";
else if(units == 3 || num == 3)
unit = "three";
else if(units == 4 || num == 4)
unit = "four";
else if(units == 5 || num == 5)
unit = "five";
else if(units == 6 || num == 6)
unit = "six";
else if(units == 7 || num == 7)
unit = "seven";
else if(units == 8 || num == 8)
unit = "eight";
else if(units == 9 || num == 9)
unit = "nine";
if(tens == 2)
ten = "twenty";
else if(tens == 3)
ten = "thirty";
else if(tens == 4)
ten = "forty";
else if(tens == 5)
ten = "fifty";
else if(tens == 6)
ten = "sixty";
else if(tens == 7)
ten = "seventy";
else if(tens == 8)
ten = "eighty";
else if(tens == 9)
ten = "ninety";
if(digit == 1)
word = unit;
else if(digit == 2)
word = ten + " " + unit;
return word;
}
//inHundreds(525, 3)
public String inHundreds(int num, int digit){
int hundreds = num/100; // =5
int tensAndUnits = num%100; // =25
String hundred = "";
String tenAndUnit = "";
String word = "";
tenAndUnit = inTens(tensAndUnits, 2);
if(hundreds == 1)
hundred = "one hundred";
else if(hundreds == 2)
hundred = "two hundred";
else if(hundreds == 3)
hundred = "three hundred";
else if(hundreds == 4)
hundred = "four hundred";
else if(hundreds == 5)
hundred = "five hundred";
else if(hundreds == 6)
hundred = "six hundred";
else if(hundreds == 7)
hundred = "seven hundred";
else if(hundreds == 8)
hundred = "eight hundred";
else if(hundreds == 9)
hundred = "nine hundred";
word = hundred + " " + tenAndUnit;
return word;
}
public String inThousands(int num, int digit){
int thousands = 0;
int hundredsAndOthers = num%1000;
String thousand = "";
String hundredAndOther = "";
String word = "";
if(digit == 5)
{
thousands = num/1000;
thousand = inTens(thousands, 2);
}
else if(digit == 4)
{
thousands = num/1000;
thousand = inTens(thousands, 1);
}
if(hundredsAndOthers/100 == 0) // in case of "023"
hundredAndOther = inTens(hundredsAndOthers, 2);
else
hundredAndOther = inHundreds(hundredsAndOthers, 3);
word = thousand + " thousand " + hundredAndOther;
return word;
}
}
import java.lang.*;
import java.io.*;
public class rupee
{
public static void main(String[] args)throws IOException
{
int len=0,revnum=0,i,dup=0,j=0,k=0;
int gvalue;
String[] ones={"one","Two","Three","Four","Five","Six","Seven","Eight","Nine","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen",""};
String[] twos={"Ten","Twenty","Thirty","Fourty","fifty","Sixty","Seventy","eighty","Ninety",""};
System.out.println("\n Enter value");
InputStreamReader b=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(b);
gvalue=Integer.parseInt(br.readLine());
if(gvalue==10)
System.out.println("Ten");
else if(gvalue==100)
System.out.println("Hundred");
else if(gvalue==1000)
System.out.println("Thousand");
dup=gvalue;
for(i=0;dup>0;i++)
{
revnum=revnum*10+dup%10;
len++;
dup=dup/10;
}
while(j<len)
{
if(gvalue<10)
{
System.out.println(ones[gvalue-1]);
}
else if(gvalue>10&&gvalue<=19)
{
System.out.println(ones[gvalue-2]);
break;
}
else if(gvalue>19&&gvalue<100)
{
k=gvalue/10;
gvalue=gvalue%10;
System.out.println(twos[k-1]);
}
else if(gvalue>100&&gvalue<1000)
{
k=gvalue/100;
gvalue=gvalue%100;
System.out.println(ones[k-1] +"Hundred");
}
else if(gvalue>=1000&&gvalue<9999)
{
k=gvalue/1000;
gvalue=gvalue%1000;
System.out.println(ones[k-1]+"Thousand");
}
else if(gvalue>=11000&&gvalue<=19000)
{
k=gvalue/1000;
gvalue=gvalue%1000;
System.out.println(twos[k-2]+"Thousand");
}
else if(gvalue>=12000&&gvalue<100000)
{
k=gvalue/10000;
gvalue=gvalue%10000;
System.out.println(ones[gvalue-1]);
}
else
{
System.out.println("");
}
j++;
}
}
}

why my label formatter is not working as expected in highcharts

I would like to do dynamic texting for my x axis's label. Basically if the label with same month year has been displayed, I do not want to repeat them.
However, in my jsfiddle example, it somehow doesn't work (even though it does return the wanted text). What am I doing wrong?
http://jsfiddle.net/daxu/md2zk/64/
if (labelYear == -1 || year != labelYear) {
$('#MessagePerformanceChartContainerID').data("FirstYear", year);
if (labelYear == -1)
{
usedLabels = [];
}
usedLabels.push(curr_month + ' ' + curr_year);
$('#MessagePerformanceChartContainerID').data("UsedLabels", usedLabels);
////first one so
return curr_month + ' ' + curr_year;
}
else{
var usedLabel = curr_month + ' ' + curr_year;
if ( $.inArray(usedLabel, usedLabels) != -1)
{
usedLabel = curr_day + ' ' + curr_month + ' ' + curr_year;
return 'a';
}
else
{
usedLabels.push(usedLabel);
$('#MessagePerformanceChartContainerID').data("UsedLabels", usedLabels);
alert(usedLabel);
return usedLabel;
}
}
Just formatter is called twice :) See JS console: http://jsfiddle.net/md2zk/66/ - each timestamp is listed twice.
As solution, I would clean up UsedLabels in tickPositioner:
$('#MessagePerformanceChartContainerID').data("UsedLabels", []);
Demo: http://jsfiddle.net/md2zk/67/

Resources