Test case:
logger.debug(formatRSUnit(559546000000l)); // 559.54B
logger.debug(formatRSUnit(19546000000l)); // 19.54B
logger.debug(formatRSUnit(1954600000l)); // 1.95B
logger.debug(formatRSUnit(155400000l)); // 155.4M
logger.debug(formatRSUnit(70000000l)); // 70.0M
logger.debug(formatRSUnit(5400000l)); // 5.40M
logger.debug(formatRSUnit(450000l)); // 450.0K
logger.debug(formatRSUnit(12000l)); // 12.0K
logger.debug(formatRSUnit(8000l)); // 8.0K
logger.debug(formatRSUnit(600l)); // 600
logger.debug(formatRSUnit(50l)); // 50
logger.debug(formatRSUnit(2l)); // 2
Source code:
private static final DecimalFormat UNIT_FORMAT = new DecimalFormat(".0#");
/**
* @author Explv (https://osbot.org/forum/profile/192661-explv/)
* @author LiveRare (https://osbot.org/forum/profile/23977-liverare/)
*
* @param value
* - An amount
* @return Formatted RS unit
*/
public static String formatRSUnit(final long value) {
String suffix;
double convertedValue;
if (value >= 1_000_000_000) {
convertedValue = ((double) value / 1_000_000_000);
suffix = "B";
} else if (value >= 1_000_000) {
convertedValue = ((double) value / 1_000_000);
suffix = "M";
} else if (value >= 1000) {
convertedValue = ((double) value / 1000);
suffix = "K";
} else {
return String.valueOf(value);
}
convertedValue = Math.floor(convertedValue * 100) / 100;
return UNIT_FORMAT.format(convertedValue) + suffix;
}
I think I've over-complicated something here. If I have, please tell me how.