最近遇到一个天坑,数字字符串(尤其是double类型的字符串)通过Double的Double.valueOf()或Double.parseDouble()获取其double值然后乘以100再取整的问题;主要是支付宝api返回单位为元的数字字符串,我们这边处理的时候出错,如下:
// 支付金额 单位 元
String totalAmount = params.get("total_amount");
// 支付金额 单位分
int totalFee = new Double(Double.valueOf(totalAmount) * 100)
.intValue();
上面这种取整的方法是错误的!!! 千万要注意 ,下面我举个例子:
import java.math.BigDecimal;
/**
* @author
* @Description:
* @date 2018年12月20日 10:45
*/
public
class SysTest {
public static
void main(String[] args) {
String total_amount = "0.29";
int totalFee1 = (int) (Double.valueOf(total_amount) * 100);
int totalFee2 = new Double(Double.valueOf(total_amount) * 100).intValue();
double totalFee3 = Double.valueOf(total_amount) * 100;
System.out.println("totalFee1:" + totalFee1);
System.out.println("totalFee2:" + totalFee2);
System.out.println("totalFee3:" + totalFee3);
System.out.println("double(total_amount):" + Double.parseDouble(total_amount));
System.out.println("double(total_amount)*100:" + new Double(Double.valueOf(total_amount) * 100)
.intValue());
System.out.println("getIntegerFromDoubleString(total_amount):" + getIntegerFromDoubleString(total_amount));
}
/**
* @param d 字符串原值(数字字符)
* @return int 返回100倍的整数原值
* @Description: double类型字符串保留2位小数返回其100倍整数原值
* @author
* @date 2018年10月19日 19:04:06
*/
public static
int getIntegerFromDoubleString(String d) {
if ("0".equals(d) || "".equals(d)) {
return 0;
}
BigDecimal b = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal bd = new BigDecimal(b.doubleValue() * 100).setScale(0, BigDecimal.ROUND_HALF_UP);
return Integer.parseInt(bd.toString());
}
/**
* @Description: 统一类型后再取整
* @author
* @date 2019年01月02日 17:38:25
* @param args
* @return
*
*/
public static void main(String[] args) {
BigDecimal a= new BigDecimal("0.29");
BigDecimal b= new BigDecimal("100");
BigDecimal ab= a.multiply(b);
int all=ab.intValue();
System.out.println("ab="+ab);
System.out.println("all="+all);
}
}
结果返回 如下:
totalFee1:28
totalFee2:28
totalFee3:28.999999999999996
double(total_amount):0.29
double(total_amount)*100:28
getIntegerFromDoubleString(total_amount):29
统一类型后再取整的方法执行结果:
ab=29.00
all=29
看见没,0.29*100=28.999999999999996,并不等于29,看到了就都注意一下,提供了解决办法就是再四舍五入一下,方法如上getIntegerFromDoubleString(str);或参考统一类型后再取整的方法;
给老板们敲代码的都注意下,不然钱无缘无故就少了........哈哈哈!