在Java中,你可以使用String.format()
方法來格式化貨幣值。為了以貨幣格式顯示數(shù)字,你需要使用特定的格式說明符。對(duì)于美元(USD),你可以使用以下格式說明符:
String currency = "0.00";
double amount = 1234.56;
String formattedCurrency = String.format("$%s", currency, amount);
System.out.println(formattedCurrency); // 輸出:$1,234.56
在這個(gè)例子中,currency
變量包含貨幣格式的字符串(包括美元符號(hào)和小數(shù)點(diǎn)后的兩位數(shù)字)。String.format()
方法將這個(gè)格式應(yīng)用于amount
變量,并將結(jié)果存儲(chǔ)在formattedCurrency
變量中。
注意,這個(gè)例子中的貨幣格式是固定的,小數(shù)點(diǎn)后總是有兩位數(shù)字。如果你需要根據(jù)用戶的地區(qū)設(shè)置自動(dòng)調(diào)整小數(shù)位數(shù),你可以使用NumberFormat
類來實(shí)現(xiàn)這一點(diǎn)。以下是一個(gè)示例:
import java.text.NumberFormat;
import java.util.Locale;
String currency = "0.00";
double amount = 1234.56;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
currencyFormatter.setMaximumFractionDigits(2);
String formattedCurrency = currencyFormatter.format(amount);
System.out.println(formattedCurrency); // 輸出:$1,234.56
在這個(gè)例子中,我們使用NumberFormat.getCurrencyInstance()
方法獲取一個(gè)針對(duì)美國(guó)地區(qū)設(shè)置的貨幣格式化對(duì)象。然后,我們使用setMaximumFractionDigits()
方法設(shè)置小數(shù)點(diǎn)后的最大位數(shù)為2。最后,我們使用format()
方法將貨幣值格式化為字符串。