DecimalFormat class

3 0 0
                                    

If you want to control the display of zeroes, you can use this java.text.DecimalFormat class.

====================

import java.text.DecimalFormat;
import java.util.Scanner;
class Class3 {
static void formattingNumber(String pattern, double num){
DecimalFormat obj = new DecimalFormat(pattern);
String myFormat = obj.format(num);

System.out.println("formatted: " + myFormat);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter an amount: ");
double input3 = scan.nextDouble();
formattingNumber("$###, ###.##", input3);
}
}

=====================

Result:

Enter an amount: 100.369formatted: $100.37

Note: The pound sign(#) represents a number or digit. The comma(,) represents a grouping separator. The period(.) represents the decimal separator. There are other patterns like leading and trailing zeroes.

Java ProgrammingWhere stories live. Discover now