Skip to content

Instantly share code, notes, and snippets.

@TylerMills
Last active December 19, 2015 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TylerMills/61085cd9f6883df9698c to your computer and use it in GitHub Desktop.
Save TylerMills/61085cd9f6883df9698c to your computer and use it in GitHub Desktop.
Sample method to convert to US cents easily for tagging CLV/LTV in Localytics
/*
Requires Unirest. Available via Maven/Gradle: http://mvnrepository.com/artifact/com.mashape.unirest/unirest-java/1.3.0
*/
import com.mashape.unirest.http.*;
import com.mashape.unirest.http.exceptions.*;
import org.json.JSONObject;
public class LLCurrencyConversion {
public static void main (String args []) {
double value = 1.99;
String base = "GBP"; // currency to convert into USD
int clv = convertToCents(value, base);
Map<String, String> values = new HashMap<String, String>();
values.put("Item Name", "T-Shirt");
values.put("Item ID", "123");
Localytics.tagEvent("Item Purchased", values, clv);
}
public static int convertToCents(double value, String base) {
int convertedValueInteger = 0;
String url = "https://api.fixer.io/latest" +
"?base=" + base +
"&symbols=USD";
try {
//parse out the conversion multiplier
HttpResponse<JsonNode> response = Unirest.get(url).asJson();
JSONObject myObj = response.getBody().getObject();
JSONObject rateObject = myObj.getJSONObject("rates");
String rate = rateObject.get("USD").toString();
//convert to numerical value
double multiplier = Double.parseDouble(rate);
//multiply by base currency rate and convert to US cents
Double convertedValueDouble = (multiplier * value * 100);
convertedValueInteger = convertedValueDouble.intValue();
return convertedValueInteger;
} catch (UnirestException ex) {
System.out.println(ex);
}
return convertedValueInteger;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment