Skip to content

Instantly share code, notes, and snippets.

@swarawan
Created November 17, 2017 10:22
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 swarawan/e2f29290f695d27d5a5b20ed849147a8 to your computer and use it in GitHub Desktop.
Save swarawan/e2f29290f695d27d5a5b20ed849147a8 to your computer and use it in GitHub Desktop.
Format Currency in ID
/**
* Return string formatted with dot separator and prepended with currency
* symbol (IDR). By default will return Rp 0.
*
* @param defaultOutput Default string to return (with currency prefix) when error happen.
*/
@NonNull
public static final String formatCurrency(@Nullable BigDecimal input, @NonNull String defaultOutput) {
if (input == null)
return defaultOutput;
try {
BigDecimal display = input.setScale(2, RoundingMode.HALF_EVEN);
NumberFormat nf = NumberFormat.getInstance(new Locale("id", "ID"));
nf.setMinimumFractionDigits(0);
nf.setMaximumFractionDigits(2);
return BuildConfig.CURRENCY_STR + nf.format(display.doubleValue());
} catch (Exception ex) {
return defaultOutput;
}
}
/**
* Return string formatted with dot separator, fixed 2 digits decimal, and prepended with
* currency symbol (IDR). By default will return Rp 0.
*/
@NonNull
public static final String formatCurrency2Digits(@Nullable String strInput) {
String defaultOutput = BuildConfig.CURRENCY_STR + "0";
if (strInput == null)
return defaultOutput;
try {
BigDecimal bdInput = new BigDecimal(strInput);
BigDecimal display = bdInput.setScale(2, RoundingMode.HALF_EVEN);
NumberFormat nf = NumberFormat.getInstance(new Locale("id", "ID"));
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return BuildConfig.CURRENCY_STR + nf.format(display.doubleValue());
} catch (Exception ex) {
return defaultOutput;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment