Last active
December 19, 2015 05:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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