的DecimalFormat 和 NumberFormat的應該只是罰款。 Currency實例可以工作更好:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Foo {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#0.00");
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
NumberFormat cf = NumberFormat.getCurrencyInstance();
System.out.printf("0 with df is: %s%n", df.format(0));
System.out.printf("0 with nf is: %s%n", nf.format(0));
System.out.printf("0 with cf is: %s%n", cf.format(0));
System.out.println();
System.out.printf("12345678.3843 with df is: %s%n",
df.format(12345678.3843));
System.out.printf("12345678.3843 with nf is: %s%n",
nf.format(12345678.3843));
System.out.printf("12345678.3843 with cf is: %s%n",
cf.format(12345678.3843));
}
}
這將輸出:
0 with df is: 0.00
0 with nf is: 0.00
0 with cf is: $0.00
12345678.3843 with df is: 12345678.38
12345678.3843 with nf is: 12,345,678.38
12345678.3843 with cf is: $12,345,678.38
你能不能給沒有工作的例子嗎? – SudoRahul
你確定嗎?我會爲我的格式字符串使用「#0.00」,但這應該並且會工作。我不得不懷疑你是否正在運行上面顯示的代碼。 –
可能是因爲你在做'Double.valueOf'。只是猜測,但。 –