shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
package com.walker.infrastructure.utils;
 
import java.text.DecimalFormat;
 
public class MoneyUtils {
 
    /**
     * 把金额(分)转成元,并强制保留2位小数。如:120 --> 1.20
     * @param fen
     * @return
     * @date 2023-20-29
     */
    public static final String scaleYuan2Accuracy(long fen){
        double yuan = fen / 100.0;
        DecimalFormat df2 = new DecimalFormat("#.##");
        String score = df2.format(yuan);
//        System.out.println("score = " + score);
        if(score.indexOf(StringUtils.SYMBOL_DOT) < 0){
            // 只有元,没有小数,需要加上
            return score + ".00";
        }
        // 存在小数,如果只有一位需要补充0
        String decimal = score.substring(score.indexOf(StringUtils.SYMBOL_DOT) + 1);
        if(decimal.length() == 2){
            return score;
        } else if(decimal.length() == 1){
            return score + "0";
        } else {
            throw new UnsupportedOperationException("没有小数,金额转换错误:" + score);
        }
    }
}