的NumberFormat是所有数字格式的抽象基类。此类提供接口,用于格式化和解析号码。
要使用数字格式,首先必须获取区域设置实例。
然后,您可以设置格式化的许多属性。就像,您可以选择显示逗号,限制小数位数,并设置最小和最大整数长度。如果你想显示区域设置的'%',那么你必须使用NumberFormat。不要将'%'作为字符串附加到结果中。你是否想显示像(3745)这样的paranthesis来代替“ - ”来表示负数,然后使用NumberFormat。像这样,有很多用途。
您可以检查JavaDoc更多的方法
这就告诉你该怎么办呢.. !!
NumberFormat numberFormat = NumberFormat.getInstance();
// setting number of decimal places
numberFormat.setMinimumFractionDigits(2);
numberFormat.setMaximumFractionDigits(2);
// you can also define the length of integer
// that is the count of digits before the decimal point
numberFormat.setMinimumIntegerDigits(1);
numberFormat.setMaximumIntegerDigits(10);
// if you want the number format to have commas
// to separate the decimals the set as true
numberFormat.setGroupingUsed(true);
// convert from integer to String
String formattedNr = numberFormat.format(12345678L);
// note that the output will have 00 in decimal place
// convert from decimal to String
numberFormat.format(12345.671D);
// format a String to number
Number n1 = null;
Number n2 = null;
n1 = numberFormat.parse("1,234");
n2 = numberFormat.parse("1.234");
// show percentage
numberFormat = NumberFormat.getPercentInstance();
numberFormat.format(0.98);
// answer will be 98%
这是你如何使用与数字格式场位置。
// Get a default NumberFormat instance.
NumberFormat numForm = NumberFormat.getInstance();
// Format some decimals using the pattern supplied above.
StringBuffer dest1 = new StringBuffer(24);
StringBuffer dest2 = new StringBuffer(24);
FieldPosition pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
dest1 = numForm.format(22.3423D, dest1, pos);
System.out.println("dest1 = " + dest1);
System.out.println("FRACTION is at: " + pos.getBeginIndex() +
", " + pos.getEndIndex());
dest2 = numForm.format(64000D, dest2, pos);
System.out.println("dest2 = " + dest2);
System.out.println("FRACTION is at: " + pos.getBeginIndex() +
", " + pos.getEndIndex());
/*
Output:
dest1 = 22.342
FRACTION is at: 3, 6
dest2 = 64,000
FRACTION is at: 6, 6
*/
你没有回答我的问题。 – Rollerball
@Rollerball对不起,我迷路了;-)希望你明白:) – Dileep