Reputation: 103
I have the following question: I would like to convert fractions like 1/2, 3/4 to spoken words in Java like "One half" or "Three quarters".
Is there any way(pseudocode) or utility in Java that produces that output receiving basically numbers
Something like:
getSpokenWords(numerator, denominator)
returns "One half"
It would be very appreciated.
Upvotes: 0
Views: 578
Reputation:
http://www.rgagnon.com/javadetails/java-0426.html
he did it with normal numbers you just need to edit it a little use his code for the nuberator and you will need a second one for the denominator to add ith or third or whatever.
Upvotes: 1
Reputation: 54074
By far the easiest and more straightforward solution especially if you are only interested in a specific set of fractions and not something general is to use a hashtable.
HashMap<String, String> hashmap = new HashMap<String, String>();
hashmap.put("1/2", "One half");
hashmap.put("3/4", "Three quarters"); etc
From there all you need to do is to convert the passed numbers to the string.
E.g.
int numerator = 1;
int denominator = 2;
String fraction = numerator + "/" + denominator;
String word = hashmap.get(fraction);
So basically:
public String getSpokenWords(int numerator, int denominator) {
String fraction = numerator + "/" + denominator;
String word = hashmap.get(fraction);
return word == null? "": word;
}
Just create a big hashmap with your cases
Upvotes: 0
Reputation: 221
There is no standard library that I know of that does that, and as far as I know, you can't make a scalable solution for this.
One approach I'd recommend is to create arrays that essentially map the numbers to their word counterparts. For example,
String[] numerators = {"One", "Two", "Three", ... // etc., until you reach your desired limit
String[] denominators = {"whole", "hal", "third", ...
Your getSpokenWords(numerator, denominator) method can then concatenate these strings and add plural endings if needed. ("Half" is listed as "hal" because of its irregular plural form, so that you can concatenate "ves" or "f" as necessary)
Edit: If you want to be clever about it, you can even use loops, division, and modulo to separate higher numbers into their places values. 525600, for example, can be separated into 525 and 600, where you can get the text equivalent of 525 (five hundred twenty five) and append "thousand" to it. Of course, getting the string "five hundred twenty five" also requires separation in itself.
Upvotes: 1
Reputation: 2820
You can implement your logic simply by using if-else
or switch
very easily in your getSpokenWords(numerator, denominator)
because you know better your expected inputs as denominator
and numerator
, as all the expected inputs by us might not be worthy & suitable for you.
You can maintain HashMap<Integer, String>
for denominator
and numerator
, Integer
being value of denominator
and numerator
and String
being their Alpha counterparts and can get()
the values from it accordingly.
Upvotes: 1