千位分隔符 thymeleaf:使用撇号

问题描述 投票:0回答:2

我正在使用 thymeleaf 来呈现我的观点。 是否可以使用 '(撇号)作为千位分隔符? 示例:我想要的是将以下示例中的 WHITESPACE 替换为撇号的值。

<span th:text="${#numbers.formatDecimal(value, 5, 'WHITESPACE', 2, 'POINT' )}"

是否有用于撇号的 NumberPointType 或其他解决方案来实现如下格式:1'000.00

formatting numbers thymeleaf apostrophe
2个回答
2
投票

如果您深入研究

enum
org.thymeleaf.util.NumberPointType
的源代码,您将看到标准
#numbers.formatDecimal
唯一可用的选项是..

public enum NumberPointType {
    POINT("POINT"),
    COMMA("COMMA"),
    WHITESPACE("WHITESPACE"),
    NONE("NONE"),
    DEFAULT("DEFAULT");
...

所以我建议您在自己的代码中创建一个自定义方法,例如

bean
utility object
,并创建您自己的函数来根据您的意愿格式化小数。

更新

public class UIutil {

/**
 * Formats a BigInteger to a thousand grouped String
 * @param number
 * @return
 */
public static String formatNumber (BigInteger number) {
    return String.format("%,d", number);
}

}

分配:

context.setVariable("formatter", new UIutil());

致电:

th:text="${formatter.formatNumber(value)}"

0
投票

就我而言。用这个。

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class CommonUtil {
    public static final String DOT = ".";

    public static String comma(BigDecimal n) {
        return comma(String.valueOf(n));
    }

    public static String comma(double n) {
        return comma(String.valueOf(n));
    }

    public static String comma(String n) {
        try {
            List<String> h = Arrays.asList(StringUtils.split(n, CommonUtil.DOT));
            String decimal = h.size() == 2 ?
                "." + h.get(1) :
                "";

            return comma(Integer.parseInt(h.get(0))) + decimal;
        } catch (Exception e) {
            log.warn("NaN <{}>", n);
            return n;
        }
    }

    public static String comma(int n) {
        return NumberFormat.getNumberInstance().format(n);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.