Skip to content

Instantly share code, notes, and snippets.

@bekce
Last active October 7, 2020 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bekce/ad8966abc58cd71e356a3e3ab00ad5a2 to your computer and use it in GitHub Desktop.
Save bekce/ad8966abc58cd71e356a3e3ab00ad5a2 to your computer and use it in GitHub Desktop.
Custom Decimal formatting in Java with custom decimal separator and thousand separator, forced fraction and decimal places options, regardless of locale.
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
public class CustomDecimalFormat {
public static DecimalFormat prepareFormat(char decimalSeparator, char thousandSeparator, boolean forceFraction, byte decimalPlaces){
String pattern = "#,###.";
if(decimalPlaces <= 0){
pattern = pattern.substring(0, pattern.length() - 1);
} else if (forceFraction) {
for (byte i = 0; i < decimalPlaces; i++) {
pattern += "0";
}
} else {
for (byte i = 0; i < decimalPlaces; i++) {
pattern += "#";
}
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator(decimalSeparator);
symbols.setGroupingSeparator(thousandSeparator);
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
return decimalFormat;
}
public static void test(){
DecimalFormat decimalFormat = prepareFormat(',', '.', false, (byte) 2);
System.out.println(decimalFormat.format(1521119122.346)); // 1.521.119.122,35
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment