nmd*_*nmd 4 java string decimal comma
我有一系列BigDecimal数字(例如:)123456.78.我想添加逗号,所以它们看起来像这样123,456.78,所以我将它们转换为字符串并使用此代码:
private static String insertCommas(String str) {
if(str.length() < 4){
return str;
}
return insertCommas(str.substring(0, str.length() - 3)) +
"," +
str.substring(str.length() - 3, str.length());
}
Run Code Online (Sandbox Code Playgroud)
要做到这一点.问题是,当我运行insertCommas(str)它打印123,456,.78.我无法想出一种方法来阻止逗号放在小数点之前.
-
另一件事,它必须适用于大数和小数,这就是为什么我使用上面的代码而不是更简单的东西.
我也尝试了DecimalFormat("#,##0.00")类似的类型,但当数字达到某一点时,它们会被零替换,使我失去有关数字的信息.
救命?
有一种更简单的方法可以做到这一点.你只需要使用SimpleDecimalFormat
private static String insertCommas(BigDecimal number) {
// for your case use this pattern -> #,##0.00
DecimalFormat df = new DecimalFormat("#,##0.00");
return df.format(number);
}
private static String insertCommas(String number) {
return insertCommas(new BigDecimal(number));
}
Run Code Online (Sandbox Code Playgroud)
您可以在这里学习新的模式和更多:DecimalFormat API
希望这可以帮助 :)
| 归档时间: |
|
| 查看次数: |
6556 次 |
| 最近记录: |