Skip to content

Commit fc7108b

Browse files
author
quding
committed
增加元与分工具类
1 parent 343f845 commit fc7108b

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package cn.mrdear.util.moneyUtil;
2+
3+
import org.apache.commons.lang3.math.NumberUtils;
4+
5+
import java.math.BigDecimal;
6+
import java.text.DecimalFormat;
7+
import java.text.NumberFormat;
8+
import java.text.ParseException;
9+
import java.util.HashMap;
10+
import java.util.Map;
11+
12+
/**
13+
* 关于金钱操作的工具类
14+
* @author Niu Li
15+
* @since 2017/3/2
16+
*/
17+
public class MoneyUtil {
18+
19+
private static final Map<String,ThreadLocal<DecimalFormat>> moneyMap = new HashMap<>();
20+
21+
private static final double CENT_RATE = 100.0;
22+
23+
/**
24+
* 获取当前线程的decimalFormat工具类,因为该类是非同步的
25+
* @param pattern 格式
26+
* @return 该实例
27+
*/
28+
private static DecimalFormat getDecimal(final String pattern){
29+
ThreadLocal<DecimalFormat> instance = moneyMap.get(pattern);
30+
if (instance == null){
31+
synchronized (MoneyUtil.class){
32+
instance = moneyMap.get(pattern);
33+
if (instance == null){
34+
instance = new ThreadLocal<DecimalFormat>(){
35+
@Override
36+
protected DecimalFormat initialValue() {
37+
return new DecimalFormat(pattern);
38+
}
39+
};
40+
}
41+
moneyMap.put(pattern,instance);
42+
}
43+
}
44+
return instance.get();
45+
}
46+
47+
/**
48+
* 分转元
49+
* @param cent 分
50+
* @return 元
51+
*/
52+
public static String cent2yuan(Long cent){
53+
return getDecimal("0.00").format(cent/CENT_RATE);
54+
}
55+
56+
/**
57+
* 元转分
58+
* @param yuan 元金额
59+
* @return 分
60+
*/
61+
public static Long yuan2cent(double yuan) {
62+
return Math.round(yuan * CENT_RATE);
63+
}
64+
}

0 commit comments

Comments
 (0)