การจัด format ของตัวเลข
posted on 09 Feb 2005 23:31 by somkiatjava.text.DecimalFormat
The java.text.DecimalFormat class provides many ways to format numbers into strings, including number of fraction digits, using a currency symbol ($12.35), scientific notation (3.085e24), percentage scaling (33%), and locale (national) formatting options (3,000.50 or 3.000,50 or 3'000,50 or ...), different patterns for positive, zero, and negative numbers, etc. These notes show only how to specify the number of fraction digits. Check the Java API documentation for other options.First, create a DecimalFormat object which specifies the format of the number. The zero before the decimal point means that at least one digit is produced, even if it is zero. The zeros after the decimal point specify how many fraction digits are produced.
import java.text.DecimalFormat;
. . .
// Create the DecimalFormat object only one time.
DecimalFormat myformat2 = new DecimalFormat("0.00");
. . .
// Use the formatting object many times.
System.out.println(myformat2.format(1.0/3.0)); // prints 0.33
This program uses the same formatting object many times. import java.text.DecimalFormat;
public class FormatTest {
public static void main(String[] args) {
DecimalFormat myformat = new DecimalFormat("0.0000");
for (int i=1; i<=10; i++) {
System.out.println(myformat.format(1.0/i));
}
}
}

#1 By (211.26.170.123) on 2005-12-20 14:16