private static String getMoneyString(String money) throws Exception{
if(!isNumber(money)){
throw new Exception("格式错误:"+money);
}
NumberFormat nf = new DecimalFormat("##.00");
BigDecimal big=new BigDecimal(money);
big.setScale(2, BigDecimal.ROUND_HALF_UP);
money=nf.format(big);
if(money.startsWith(".")){
money="0"+money;
}
return money;
}
private static boolean isNumber(String str) {
Pattern pattern = Pattern.compile("[-+]?[0-9]+.?[0-9]+");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
private static String getMoneyString(BigDecimal big) throws Exception{
if(big==null){
big=new BigDecimal("0.00");
}
big.setScale(2, BigDecimal.ROUND_HALF_UP);
String money=big.toString();
NumberFormat nf = new DecimalFormat("##.00");
money=nf.format(big);
if(money.startsWith(".")){
money="0"+money;
}
return money;
}
public static void main(String[] args) throws Exception{
String m="0.08";
BigDecimal big=new BigDecimal("2.33");
System.out.println(getMoneyString(m));
}
钱,金额,money的格式化输出
最新推荐文章于 2023-12-02 19:58:53 发布
本文介绍了一个用于处理金额字符串的方法,该方法确保输入的数值能够被正确地格式化为带有两位小数的标准货币形式,并提供了异常处理机制以确保非标准输入也能得到妥善处理。
474

被折叠的 条评论
为什么被折叠?



