金额转换常用方法

不管是做银行的接口,还是一般支付公司的接口,都会用到一些
相关的接口,一般接口对传递的金额都会有相关的要求,一般都是以
分为单位,要转换其实并不难,但很多情况下就是怕出错,钱啊!!
所以小心了还得小心,金额中最忌讳的就是double和int的混合运算
了,本机上不出问题,草草测试的后果就不堪设想,用户的数据千奇
百怪,一不小心就是大问题,我这里写了两个常用的方法,我的想法
是减少运算,尽量是字符串操作,减少出错!仅供参考!

希望在这里能抛砖引玉!

/**
* 将以分为单位的字符串转换为double类型
* @param s
* @return
*/
public static double str2Double(String s) {
double r = 0.0;
int k = Integer.parseInt(s);
String ss = String.format("%1$012d", k);
System.out.println(ss);

StringBuffer sb = new StringBuffer();
sb.append(ss.substring(0, 10));
sb.append(".");
sb.append(ss.substring(10));

r = Double.parseDouble(sb.toString());
return r;
}

/**
* 拿取去掉小数点的金额
* @param amount
* @return
*/
public static String getAmountStr(double amount) {
//amount*100不能超过int的最大值 订单交易金额,12位长度,左补0,必填,单位为分
String TransAmt = "";
String amountStr = amount+"";
int _tempAmt = Integer.parseInt(amountStr.replaceAll("\\.",""));
if(amountStr.matches("[0-9]+\\.[0-9]{2}")){
TransAmt = String.format("%1$012d", _tempAmt);
} else if(amountStr.matches("[0-9]+\\.[0-9]{1}")) {
TransAmt = String.format("%1$011d0", _tempAmt);
} else if(amountStr.matches("[0-9]+")) {
TransAmt = String.format("%1$010d00", _tempAmt);
}
return TransAmt.replaceAll("^0+", "");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值