ืืื ืฉืืืช Java string.format()?
ืฉืืืช Java string format() ืืฉืืฉืช ืืขืืฆืื ืืืจืืืืช, ืืกืคืจืื ืฉืืืื, ืขืจืืื ืขืฉืจืื ืืื ืืื ืืืื, ืขื ืืื ืฉืืืืฉ ืืืคืจืื ืคืืจืืืื ืฉืื ืื. ืฉืืื ืื ืืืืืจื ืืช ืืืืจืืืช ืืืขืืฆืืช ืืืืฆืขืืช ืืืงืื ืื ืชืื, ืืคืืจืื ืฉืฆืืื ืืืืจืืืื ืืื. ืื ืื ืืกืืคืง ืืงืื, ืืื ืืฉืชืืฉ ืืืชืืืช ืืจืืจืช ืืืืื ืืขืืฆืื ืืืืจืืืืช. ื- string.format() ืืื ืืฉืืื ืืกืืืืช ืฉื ืืืืืงื Java String .![ืคืืจืื Java String() - 1](https://cdn.codegym.cc/images/article/c3dbc5c3-ffbd-45fe-8404-615a47cbfa69/800.jpeg)
public static String format(Locale loc, String format, Objectโฆ args)
public static String format(String format, Objectโฆ args)
ืคืจืืืจืื
- ืขืจื ืืืงืื ืฉืืืืฉื ืืฉืืืช format() .
- ืฆืืื ืืคืืจืื ืฉื ืืืจืืืช ืืคืื.
- ืืกืคืจ ืืืจืืืื ืืื ืขืืืจ ืืืจืืืช ืืคืืจืื ื ืข ืืื 0 ืืจืืื.
- NullPointerException , ืื ืืคืืจืื ืืื null ืื NullPointerException ื ืืจืง.
- IllegalFormatException , ืื ืืคืืจืื ืฉืฆืืื ืืื ื ืืืงื, ืื ืฉืื ืกืืคืงื ืืจืืืื ืืื ืืกืคืืงืื, ืืืจืื ืืื ื ืืจืง.
ืืคืจืื ืคืืจืื
ืืื ื ืกืชืื ืขื ืืื ืืคืจืืื ื ืคืืฆืื.ืืคืจื | ืชืืืืจ |
---|---|
%s, %S | ืืขืฆื ืืืจืืืช. |
%d | ืืกืคืจ ืฉืื ืขืฉืจืื ื, ืืืฉืืฉ ืขืืืจ ืืกืคืจืื ืฉืืืื ืืืื. |
%o | ืืกืคืจ ืฉืื ืืืงืืื, ืืืฉืืฉ ืขืืืจ ืืกืคืจืื ืฉืืืื ืืืื. |
%f, %F | ืขืืืจ ืืกืคืจืื ืขืฉืจืื ืืื, ืืฉืืฉ ืืืกืคืจื ื ืงืืื ืฆืคื. |
%x, %X | ืืกืคืจ ืฉืื ืืงืกืืฆืืืื, ืืืฉืืฉ ืขืืืจ ืืกืคืจืื ืฉืืืื ืืืื. |
ืฉืืืืช Java String.format() ืืืืืืืช
class Main {
public static void main(String[] args) {
// Integer value
System.out.println(String.format("%d", 234));
// String value
System.out.println(String.format("%s", "format() method"));
// Float value
System.out.println(String.format("%f", 99.99));
// Hexadecimal value
System.out.println(String.format("%x", 99));
// Char value
System.out.println(String.format("%c", 'f'));
// Octal value
System.out.println(String.format("%o", 99));
}
}
ืชึฐืคืึผืงึธื
ืฉืืืช 234 format() 99.990000 63 f 143
ืืืืื
class Main {
public static void main(String[] args) {
int n1 = 99;
// using two different specifiers for formatting the string
System.out.println(String.format("%s\nhexadecimal: %x", "Result is", n1));
}
}
ืชึฐืคืึผืงึธื
ืืชืืฆืื ืืื ืืงืกืืฆืืืืืช: 63
ืืืืื
// to use Locale
import java.util.Locale;
class Main {
public static void main(String[] args) {
int number = 9999999;
// using the default locale if none specified
System.out.println(String.format("Number: %,d", number););
// using the GERMAN locale as the first argument
System.out.println(String.format(Locale.GERMAN, "Number in German: %,d", number));
}
}
ืชึฐืคืึผืงึธื
ืืกืคืจ: 9,999,999 ืืกืคืจ ืืืจืื ืืช: 9.999.999
GO TO FULL VERSION