1、随机金额为最大值与最小值之间的二位小数
/**
* 获取随机券金额
* 随机金额为最大值与最小值之间的二位小数。
* @param maxValue,minValue
* @return newrandomNum
*/
private BigDecimal getValue(BigDecimal maxValue ,BigDecimal minValue){
double randomNum = Math.round((Math.random()*(maxValue.doubleValue() - minValue.doubleValue()) + minValue.doubleValue()) * 100);
DecimalFormat dfm = new DecimalFormat ("00");
String newrandomNum = dfm.format(randomNum);
return BigDecimal.valueOf(Double.parseDouble(newrandomNum)).divide(new BigDecimal(100));
}
public static void main(String[] args) {
Map<BigDecimal, Integer> map = new HashMap<BigDecimal, Integer>();
BigDecimal maxValue = new BigDecimal(8);
BigDecimal minValue = new BigDecimal(3);
for(int i=0; i<10000; i++){
BigDecimal b = new BaseSendCouponServiceImpl().getValue(maxValue,minValue);
if(map.get(b) == null){
map.put(b, 1);
} else {
map.put(b, map.get(b) + 1);
}
}
for(Map.Entry entry:map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
2、随机金额为最大值与最小值之间的整数
private BigDecimal getValue(BigDecimal maxValue ,BigDecimal minValue){
double randomNum = Math.round((Math.random()*(maxValue.doubleValue() - minValue.doubleValue()) + minValue.doubleValue()));
DecimalFormat dfm = new DecimalFormat ("00");
String newrandomNum = dfm.format(randomNum);
return BigDecimal.valueOf(Double.parseDouble(newrandomNum));
}
public static void main(String[] args) {
Map<BigDecimal, Integer> map = new HashMap<BigDecimal, Integer>();
BigDecimal maxValue = new BigDecimal(8);
BigDecimal minValue = new BigDecimal(3);
for(int i=0; i<100000; i++){
BigDecimal b = new BaseSendCouponServiceImpl().getValue(maxValue,minValue);
if(map.get(b) == null){
map.put(b, 1);
} else {
map.put(b, map.get(b) + 1);
}
}
for(Map.Entry entry:map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
3、同事写的
public static BigDecimal getRandomValueBetween(BigDecimal maxValue, BigDecimal minValue) {
if (maxValue == null || minValue == null) {
return BigDecimal.ZERO;
}
BigDecimal factor = new BigDecimal(new Random().nextInt(101) ).divide(new BigDecimal(100.00));
BigDecimal randomNum = factor.multiply(maxValue.subtract(minValue).add(minValue)).setScale(1, BigDecimal.ROUND_HALF_UP);
return randomNum;
}