Last active
March 9, 2023 11:10
-
-
Save adojos/4c8d7923a6dcd7cdc6ac489ba6c59bdc to your computer and use it in GitHub Desktop.
Java: Format Decimal Number Using Pattern #java
This file contains hidden or 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; | |
public class DecimalFormatter { | |
public static void main(String[] args) { | |
double dbNum = 170180.24523D; // number to be formatted | |
/* Basic Formatting Process */ | |
String strPattern = "######.#####"; // desired formatting pattern | |
DecimalFormat decimalFormat = new DecimalFormat(strPattern); | |
String strFormattedNum = decimalFormat.format(dbNum); // now format the number | |
System.out.println(dbNum + " -> " + strFormattedNum); // output = 170180.24523 | |
/* More Formatting Examples */ | |
strPattern = "######.###"; // To print full integer but only 3 decimal places | |
decimalFormat = new DecimalFormat(strPattern); | |
strFormattedNum = decimalFormat.format(dbNum); | |
System.out.println(dbNum + " -> " + strFormattedNum); // output = 170180.245 | |
strPattern = "######.000000"; // To print extra 0 in decimal value | |
decimalFormat = new DecimalFormat(strPattern); | |
strFormattedNum = decimalFormat.format(dbNum); | |
System.out.println(dbNum + " -> " + strFormattedNum); // output = 170180.245230 | |
strPattern = "#"; // To print only integer value part | |
decimalFormat = new DecimalFormat(strPattern); | |
strFormattedNum = decimalFormat.format(dbNum); | |
System.out.println(dbNum + " -> " + strFormattedNum); // output = 170180 | |
strPattern = "0000000.###"; // To print extra zero in integer part and 3 decimal places | |
decimalFormat = new DecimalFormat(strPattern); | |
strFormattedNum = decimalFormat.format(dbNum); | |
System.out.println(dbNum + " -> " + strFormattedNum); // output = 0170180.245 | |
strPattern = "#.##%"; // multiply by 100 and display as % with 3 deci places | |
decimalFormat = new DecimalFormat(strPattern); | |
strFormattedNum = decimalFormat.format(dbNum); | |
System.out.println(dbNum + " -> " + strFormattedNum); // output = 17018024.52% | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment