Simple Currency Conversion using Google Calculator and Java
on Jan 06, 2011 in Coding, JavaScript, Trading Technology by Marc McIntyreHere’s a little trick that I use to generate seed values for some of our mock components to ensure these values are fairly realistic.
Google has a web service that when queried returns a JSON string for calculated values. It’s basically a web service for the extremely useful Google Calculator.
If you point your browser to http://www.google.com/ig/calculator?hl=en&q=1GBP%3D%3FAUD you can see the result for yourself. I’ve wrapped this service in a small java class to demonstrate how to perform these types of calculations programmatically. The class makes use of GSON, which is another really useful Google API for converting JSON objects into POJOs.
package com.caplin.datasrc.ret.ct;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import com.google.gson.Gson;
public class SeedGenerator
{
static class Result
{
private String lhs;
private String rhs;
public String getLhs()
{
return lhs;
}
public String getRhs()
{
return rhs;
}
public void setLhs(String lhs)
{
this.lhs = lhs;
}
public void setRhs(String rhs)
{
this.rhs = rhs;
}
}
public static void main(String[] args) throws Exception
{
String google = "http://www.google.com/ig/calculator?hl=en&q=";
String baseCurrency = "GBP";
String termCurrency = "AUD";
String charset = "UTF-8";
URL url = new URL(google + baseCurrency + "%3D%3F" + termCurrency);
Reader reader = new InputStreamReader(url.openStream(), charset);
Result result = new Gson().fromJson(reader, Result.class);
// Get the value without the term currency.
String amount = result.getRhs().split("\\s+")[0];
System.out.println(amount);
}
}
The beauty of Google Calculator is of course that it can be used for any conversion. If you point your browser to http://www.google.com/ig/calculator?hl=en&q=1%20mile=?kilometer you will get the following result:
{lhs: "1 mile",rhs: "1.609344 kilometers",error: "",icc: false}
Even extremely arbitrary calculations work! For example http://www.google.com/ig/calculator?hl=en&q=furlongs%20in%20light%20year produces:
{lhs: "1 light year",rhs: "4.70279985 \x26#215; 10\x3csup\x3e13\x3c/sup\x3e furlongs",error: "",icc: false}
which looks like 4.70279985 × 1013. Pretty cool!

great!
thanks for sharing
Nice one .. It is very helpful for me
Thanks
sounds about right – 1 light year is about 4000 furlongs….maybe not
Thanx really helpful.
As i did experiments hope the url should be in this format
“http://www.google.com/ig/calculator?hl=en&q=1GBP=?USD”
isn’t that your code doesn’t add the initial amount to the url ? hope it have to be there just after “q=”.