MathUtil.java
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.framework.util;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 数字计算帮助类
* @author 61004
*
*/
public class MathUtil {
public static boolean isNumber(String str) {
Pattern pattern = Pattern.compile("^[0-9]+(\\.[0-9]*)?$");
Matcher match=pattern.matcher(str);
return match.matches();
}
/**
*
* @param num1 分子
* @param num2 分母
* @return
*/
public static String percentage(float num1,float num2) {
// 创建一个数值格式化对象
NumberFormat numberFormat = NumberFormat.getInstance();
// 设置精确到小数点后2位
numberFormat.setMaximumFractionDigits(2);
String result = numberFormat.format(num1 / num2 * 100);
return result + "%";
}
/**
* 判断两个数字相差是否超过10%
* @param n1
* @param n2
* @return
*/
public static boolean isHign10Per(double n1,double n2) {
if(n1 ==0 || n2==0) {
return true;
}
return Math.abs(n1-n2)/n1 >= 0.1;
}
/**
* 获取两个数字相差百分比
* @param n1
* @param n2
* @return
*/
public static String getHighPer(double n1,double n2) {
String result = "%";
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(2);
if(n1 ==0 || n2 ==0) {
// 设置精确到小数点后2位
result = numberFormat.format(Math.abs(n1-n2)*100) +"%";
}else{
result = numberFormat.format((Math.abs(n1-n2)/n1)*100) +"%";
}
return result;
}
//保留两位小数
public static Double keepTwoDecimalPlaces(Double num) {
if(null==num || 0==num){
return null;
}
BigDecimal bg = new BigDecimal(num);
return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void main(String[] args) {
System.out.println(MathUtil.keepTwoDecimalPlaces(0.781));
}
}