Java 正则校验金额,只能是正整数或2位小数以内

原文:https://my.oschina.net/zjllovecode/blog/2986865 

public class Test {

    public static boolean isNumber(String str) {
        Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        Matcher match = pattern.matcher(str);
        return match.matches();
    }

    public static void main(String[] args) {

        boolean a = isNumber("1");
        boolean b = isNumber("1.0");
        boolean c = isNumber("1.22");
        boolean d = isNumber("1.222");
        boolean e = isNumber("222.22");
        boolean f = isNumber("0.01");
        boolean g = isNumber("0.001");
        boolean h = isNumber("");
        boolean i = isNumber("1.");

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);
        System.out.println(f);
        System.out.println(g);
        System.out.println(h);
        System.out.println(i);

        Double amountD = Double.parseDouble("1.");
        Long fronezAmount = BigDecimal.valueOf(amountD * 100).toBigInteger().longValue();
        System.out.println(amountD);
        System.out.println(fronezAmount);
    }
}

测试结果:

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值