Back
TAGS
SHARE
  • X
  • facebook
  • linkedin
  • tabler

Simple Currency Conversion using Google Calculator and Java

Here’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!

Want to know more?

Talk to our team

We’ll help you find the right products and solutions for your business.

Enter your details

Testimonial
Testimonial

Rodney Chetty, Standard Bank

Caplin’s suite of products form a key part of how we do business with our clients. The Caplin team provide a great technology solution and strong business partnership that supports our aspirations

ALSO Trusted BY
  • Uni Credit
  • Natwest
  • Santander