我使用下面的代码尝试在Android中将Double格式化为字符串:
DecimalFormat decimalFormat = new DecimalFormat("USD ###,###,##0.00");
String result = decimalFormat.format(87359.0);我正在寻找“美元87,359.00”,但我得到“美元87.359,00”在一些设备。
有什么想法吗?
发布于 2018-01-19 06:10:19
DecimalFormat是本地化的。如果未指定Locale,则DecimalFormat将使用用户在其设备上设置的Locale。
如果出于某种原因,您希望覆盖用户为其设备设置的Locale,则可以执行以下操作:
private String formatMyCurrency(double d){
String result = "";
try{
String pattern = "USD ###,###,##0.00";
//Use which ever locale you need
//If you would rather have $ instead of USD you can use NumberFormat.getCurrencyInstance(Locale.US) and adjust your pattern
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
result = df.format(d);
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
return result;
}或者你可以这样做(,但是,我不推荐这样做!):
private String formatMyCurrency(double d){
String result = "";
try{
String pattern = "USD ###,###,##0.00";
String sep = ".,";
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(sep.charAt(0));
dfs.setGroupingSeparator(sep.charAt(1));
DecimalFormat df = new DecimalFormat(pattern, dfs);
result = df.format(d);
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
return result;
}免责声明
上面的代码是在标准文本编辑器中编写的-因此,一些方法名称可能不正确,或者代码中的某个位置可能存在语法错误
https://stackoverflow.com/questions/48330384
复制相似问题