File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
Util-Demo/src/main/java/cn/mrdear/util/moneyUtil Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments