问题
I have an amount
Long amount=83000;
I need to format it to $83.000
, how to do this ?
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
String moneyString = formatter.format(amount);
System.out.println(moneyString);
I am getting $83000.00
but i want my point before 3 last digit
回答1:
This should work :
DecimalFormatSymbols symbols = new DecimalFormatSymbols(new Locale("en", "US"));
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat("$#,##0", symbols);
System.out.println(df.format(83000L));
//$83.000
回答2:
This may help you,
DecimalFormat myFormatter = new DecimalFormat("$###,###.###");
String output = myFormatter.format(amount);
System.out.println(output);
回答3:
You are using the wrong class. NumberFormatter will give Locale specific formatting. From the API docs:
Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.
You should rather look into DecimalFormat if you intend to output the same string regardless of the operating system's current locale.
By creating a formatting string such as "$#,##0"
and passing an instance of DecimalFormatSymbols where you set the grouping character to '.'
you will achieve your intended output without hacks.
回答4:
How about this?
long num = 83000;
DecimalFormat df = new DecimalFormat("##,###");
String toReplace = df.format(83000).toString();
System.out.println(toReplace.replace(",", "."));
回答5:
Perhaps you meant this?
public static void main(String[] args) {
Long amount = 67890L;
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
String moneyString = formatter.format((double) amount / 1000);
System.out.println(moneyString);
}
This code will print:
$67.89
回答6:
Use BigDecimal
for formatting instead of Long
:
BigDecimal bd = BigDecimal.valueOf(amount, 3);
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en","US"));
formatter.setMinimumFractionDigits(3);
String moneyString = formatter.format(bd);
System.out.println(moneyString);
来源:https://stackoverflow.com/questions/26338025/how-to-format-this-string