Created
November 17, 2017 10:22
-
-
Save swarawan/e2f29290f695d27d5a5b20ed849147a8 to your computer and use it in GitHub Desktop.
Format Currency in ID
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
/** | |
* 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