Last active
October 7, 2020 06:29
-
-
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.
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
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