Thymeleaf:将逗号双精度数转换为点双精度数

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

我有以下代码:

  <td><input type="number" step="0.00000001" th:value="${product.getNumber()}" name="number"/></td>

getNumber
返回普通双精度值,如
1.0E-8

我的问题是:

  1. 我希望它不显示 1.0E-8,而是应该显示 0.00000001。

  2. 此外,像 0.0001 这样的数字用逗号表示,例如 0,0001

我尝试使用它http://www.thymeleaf.org/apidocs/thymeleaf/2.0.15/org/thymeleaf/expression/Numbers.html但没有成功。

知道如何实现这一目标吗?

谢谢

html thymeleaf
2个回答
2
投票

您可以使用 Thymeleaf (

API
) 中的 #numbers 实用程序并相应地设置数字。

th:value="${#numbers.formatDecimal(product.number, 2, 3)}"

这设置最小整数位数(上面的 2 个)和精确的小数位数(上面的 3 个)。

对于分隔符,可以直接指定:

th:value="${#numbers.formatDecimal(product.number, 2, 3,'COMMA')}"

分隔符选项为

POINT
COMMA
WHITESPACE
NONE
DEFAULT
(按区域设置)。

请记住,浏览器可能采用不同的规则,在某些情况下您可能希望使用

step="any"
。 (对于直接使用
th:text
打印,这没关系。)


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.