import java.math.BigDecimal;
import java.text.DecimalFormat;
public class TestMoney {
/**
* 提供精确的乘法运算。
*
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(BigDecimal b1, BigDecimal b2) {
return b1.multiply(b2).doubleValue();
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
System.out.println("************************************************");
//生成随机订单金额
// double a = Math.random() * 10000;
double a = Math.random() * 86;
//格式化订单金额
DecimalFormat df = new DecimalFormat("0");
String orderPrice = df.format(a);
System.out.println("随机订单金额:" + orderPrice);
//生成随机账户余额
double userMoney = Math.random() * 10000;
//格式化账户余额
DecimalFormat dfUserMoney = new DecimalFormat("0.00");
String strUserMoney = dfUserMoney.format(userMoney);
BigDecimal userCountMoney = new BigDecimal(strUserMoney);
System.out.println("随机账户余额:" + strUserMoney);
//订单金额
BigDecimal orderCountPrice = new BigDecimal(orderPrice);
System.out.println("订单金额:"+orderCountPrice);
//服务费百分比 0.01即1%
BigDecimal serviceFee = new BigDecimal("0.01");
//计算服务费 总金额*服务费百分百
BigDecimal serviceMoney = orderCountPrice.multiply(serviceFee);
double mul = mul(serviceFee, orderCountPrice);
System.out.println("服务费(计算后未处理):" + serviceMoney);
System.out.println("服务费(doubleValue()方式):" + serviceMoney.doubleValue());
//取值并保留2位小数
BigDecimal money = serviceMoney.setScale(2, BigDecimal.ROUND_DOWN);
System.out.println("服务费(保留两位小数):" + money);
//计算用户所得金额 订单金额-服务费
BigDecimal yesGetMoney = orderCountPrice.subtract(money);
System.out.println("用户所得金额(扣除服务费后):"+yesGetMoney);
//更新用户账户余额
BigDecimal itemUserMoney = userCountMoney.add(yesGetMoney);
System.out.println("更新前余额:"+userCountMoney);
System.out.println("账户余额:"+itemUserMoney);
}
}
}