net.lulihu.ObjectKit.NumberKit Maven / Gradle / Ivy
package net.lulihu.ObjectKit;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
/**
* 数字工具类
*/
public class NumberKit {
private NumberKit() {
}
/**
* 获取最接近的最大2的指数次幂 一定大于本身
*
* @param a 数值
*/
public static int getClosest2IndexGreaterThanSelf(int a) {
if (a == 1) return 2;
int closest2Index = getClosest2Index(a);
if (closest2Index <= a) {
return getClosest2IndexGreaterThanSelf(a + 1);
}
return closest2Index;
}
/**
* 获取最接近的最大2的指数次幂,可能为其本身
*
* @param a 数值
*/
public static int getClosest2Index(int a) {
int n = a - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return n + 1;
}
/*-------------------------------------------format-----------------------------------------------*/
/**
* 保留指定位数的小数(少的位数不补零)
*/
public static double keepRandomPointDouble(double var1, int n) {
return new BigDecimal(var1).setScale(n, RoundingMode.HALF_UP).doubleValue();
}
/**
* 保留指定位数的小数(少的位数不补零)
*/
public static String keepRandomPoint(Double value, int n) {
if (value == null) {
value = 0.00;
return new BigDecimal(value).setScale(n, RoundingMode.HALF_UP).toString();
} else {
return new BigDecimal(value).setScale(n, RoundingMode.HALF_UP).toString();
}
}
/**
* 浮点保留两位小数(少的位数不补零)
*/
public static String keep2Point(double value) {
return keepRandomPoint(value, 2);
}
/**
* 浮点保留1位小数(少的位数不补零)
*/
public static String keep1Point(double value) {
return keepRandomPoint(value, 1);
}
/**
* 浮点保留任意位小数(少位补零)
*/
public static String keepRandomPointZero(double value, int n) {
DecimalFormat df = new DecimalFormat("#0.00");
return df.format(Double.valueOf(keepRandomPoint(value, n)));
}
/**
* 浮点保留两位小数(少位补零)
*/
public static String keep2PointZero(double value) {
return keepRandomPointZero(value, 2);
}
/**
* 获取任意小数点位的百分比表示
*/
public static String percentRandomPoint(double value, int n) {
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setGroupingUsed(false);
percent.setMaximumFractionDigits(n);
return percent.format(value);
}
/**
* result = var1/var2
* 就算结果百分比保留两位小数
*
* @param var1 被除数
* @param var2 除数
*/
public static String percent2Point(double var1, double var2) {
if (var1 == 0D) return NumberKit.percent2Point(0.0D);
if (var2 == 0D) return NumberKit.percent2Point(1.0D);
return percentRandomPoint(var1 / var2, 2);
}
/**
* 百分比保留两位小数
*/
public static String percent2Point(double value) {
return percentRandomPoint(value, 2);
}
/**
* 获取格式化经纬度后的小数(保留3位)
*/
public static String latLngPoint(double value) {
return keepRandomPoint(value, 3);
}
/**
* 生成指定范围内的随机数
*
* @param min 最小值
* @param max 最大值
* @return 指定范围内的随机数
*/
public static int rangeRandomNumber(int min, int max) {
if (max < min) throw new NumberFormatException("最大值小于最小值无法生成随机数...");
Random random = new Random();
return random.nextInt(max) % (max - min + 1) + min;
}
}