I'm trying to figure out how to reformat a long value that I get from an API. The long value represents a stock's market cap so naturally it varies, but essentially what I would like is to round up and abbreviate.
I've found on here a code to abbreviate the number down depending on how high it is, but I can't figure out how to keep decimals.
For example if I query "NFLX" I get back "117173403648". With the code I would get back 117B. What I would like the output to be is "117.17B".
I have tried Math.round() function before I abbreviate the number, but it does not seem to work the way I want it to, nor does DecimalFormat. Surely I'm using both wrong.
here is the code I found and modified on SO:
public static String abbreviateNumber(long marketCap) {
long temp = marketCap / 1000000000;
if (temp > 0) {
return temp + "B";
}
temp = marketCap / 1000000;
if (temp > 0) {
return temp + "M";
}
temp = marketCap / 1000;
if (temp > 0) {
return temp + "K";
}
return String.valueOf(marketCap);
}
Using this the output of marketCap is 117B, but I would like to have 2 decimals, and still keep this abbreviation method.
Thanks, any help is greatly appreciated. I'm new to programming and figuring it out as I go.