redis缓存中得分相同时按时间排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/superit401/article/details/82629751

核心提示时间戳2040年1月1日(这个时间可自定义)距离当前时间的毫秒值之差作为小数部分,得分(整数)作为整数部分,存入缓存;从缓存取出得分时截取整数部分即为真正得分

注意数字太大会有带字母E的科学计数法干扰

工具类NumberUtils.java:

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class NumberUtil {
	//判断是否为(正/负)整数或小数
	public static  boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("^[-]*[0-9]+(.[0-9]+)?$");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
	}
	
	//分数加时间戳转成double:整数部分是分数,小数部分是时间戳
	public static Double strTime2Double(String score,String flag) throws ParseException{
		if(StringUtils.isBlank(score) || !isNumeric(score)){
			return 0.0;
		}
		
		if ("1".equals(flag)) {
			long nowSecond = System.currentTimeMillis();
			String str = "2040-01-01 08:00:00.001";
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
		    Date date = sdf.parse(str);
		    long diff = date.getTime() - nowSecond;
			String scoreStr = score +"."+ diff;
			Double scoreDouble = Double.parseDouble(scoreStr);
			return scoreDouble;
		}
		double sd = Double.parseDouble(score);
		return sd;
	}
	
    //取整数部分
	public static Long round(Double score){
		String scoreStr = "";
		if(isENum(score+"")){
			BigDecimal bd = new BigDecimal(score+"");
			scoreStr = bd.toPlainString();
		}else{
			scoreStr = score+"";
		}
		String intStr = scoreStr.split("\\.")[0];
		long scoreL = Long.parseLong(intStr);
		return scoreL;
	}
	
	//判断是否为科学计算法
	static String regx = "^((-?\\d+.?\\d*)[Ee]{1}(-?\\d+))$";//科学计数法正则表达式
    static Pattern pattern = Pattern.compile(regx);
    public static boolean isENum(String input){//判断输入字符串是否为科学计数法
        return pattern.matcher(input).matches();
    }
	
	public static void main(String[] args) {
		double a;
		try {
			a = strTime2Double("999999999999.9999999999","1");
			System.out.println("a:"+a);//a:1.0E12
			System.out.println(a==999999999999.9999999999);//true
			System.out.println(Math.floor(123.34));//123.0
			System.out.println(Math.floor(199999999999.9999999999)==199999999999.0);//false
			System.out.println(Math.round(199999999999.9999999999)==199999999999L);//false
			System.out.println(Math.round(199999.9999999999));//200000
			System.out.println(Math.ceil(199999999999.9999999999)==199999999999L);//false
			System.out.println(Math.ceil(239999.9999999999));//240000.0
			System.out.println("1223456700005.9999999999".split("\\.")[0]);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

注意:redis支持包括小数点在内的17为数字(double类型包括整数和小数部分)

猜你喜欢

转载自blog.csdn.net/superit401/article/details/82629751
今日推荐