import java.math.BigDecimal;
public class Demo {
public static Double[] types = { 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0 };// 人民币币种
public static void main(String[] args) {
Double toMoney = 100.0;// 用于支付的100元
Double tpendMoney = 81.99;// 实际花费81.99元
Double over = DoubleFormat(toMoney - tpendMoney);
System.out.println("找零" + over);
String calc = calc(over);
System.out.println(calc);
}
public static String calc(Double over) {
String resultString = "";
for (int i = 0; i < types.length; i++) {
if (types[i] >= over) {
if (types[i].equals(over)) {
return types[i].toString();
} else {
resultString += types[i - 1];
resultString += "\t" + calc(DoubleFormat(over - types[i - 1]));
break;
}
}
}
return resultString;
}
public static Double DoubleFormat(Double d) {
BigDecimal bd = new BigDecimal(d);
return bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
结果:
找零18.01
面值:10.0 , 5.0 , 2.0 , 1.0, 0.01