Freemarker数字格式化总结

https://blog.csdn.net/wangmeng951011/article/details/70568311

前言
我们都知道,在我们套页面的时候一定要注意的一点就是数字的展示,因为稍有不慎,你的页面上就可能出现0.60000000001这种的数字,如果是价格的话,那还真的是比较的尴尬!因此在我们的代码层面我们是一定需要做好相关的数字格式化的准备的,当然,这并不意味这在前端页面上我们就可以不做任何事情!毕竟双重保险来的更加妥当一些。

数字格式化
string (when used with a numerical value)
        Converts a number to a string. In its simplest form (expression?string) it uses the default format that the programmer has specified via the number_format and the locale configuration settings. You can also specify a number format explicitly with this built-in, as it will be shown later.
        There are four predefined number formats: computer, currency, number, and percent. The exact meaning of these is locale (nationality) specific, and is controlled by the Java platform installation, not by FreeMarker, except for computer, which uses the same formatting as the c built-in. There can also be programmer-defined formats, whose name starts with @ (programmers see more here…).

        这是其官网上给出的一段关于数字类型如何转为string字符串然后予以显示的答案。大意是说如果我们遇到了数字值,最好是利用其提供的方式转化为相应的字符串。下面我们来具体的看几个例子!

1、货币展示
        实际上我们在日常的开发过程中遇到的比较多的问题就是货币的展示,对于货币而言,在不同的地区是有不同的符号的。因此,freemarker为我们提供了方便的方式实现。

<#assign x=42>
${x?string.currency}

        上述的表达式最终的结果将是¥42.00,这个功能看起来很不错!

2、百分数展示
        百分数也是我们在日常的开发过程中遇到的比较多的问题,其展示的方案如下。当然变量我们依旧使用上面的变量。

${x?string.percent}

        其最终的结果将是4,200%,看上去不赖!

3、数字格式化
        上面所说的例子是比较典型的数字展示的例子,下面所说的就是数字的格式化,其实如果数据来源于我们的接口还好,如果是来自第三方或者外部平台的接口,那可真的是一定要小心。稍不留神,就可能闹出大笑话!
        下面的话,我首先列举出一些例子,大家猜猜最终的格式化结果!

<#assign x = 1.234>
${x?string["0"]}
${x?string["0.#"]}
${x?string["0.##"]}
${x?string["0.###"]}
${x?string["0.####"]}

${1?string["000.00"]}
${12.1?string["000.00"]}
${123.456?string["000.00"]}

${1.2?string["0"]}
${1.8?string["0"]}
${1.5?string["0"]} <-- 1.5, rounded towards even neighbor
${2.5?string["0"]} <-- 2.5, rounded towards even neighbor

${12345?string["0.##E0"]}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        下面就是揭晓答案的时候,不知道各位看官猜的准不准呢!

1
1.2
1.23
1.234
1.234

001.00
012.10
123.46

1
2
2 <-- 1.5, rounded towards even neighbor
2 <-- 2.5, rounded towards even neighbor

1.23E4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        大家可以看到这里的话主要分为三类,第一类就是规定后面的小数位数,当然在这种情况下如果后面不足规定的位数是不会自动补齐的。
第二类就是不仅规定了小数的位数,还在位数不足规定位数的时候自动补齐。
最后就是四舍五入的相关规则。当然还有科学计数法的实现!

总结
        如上我们总结了在日常的开发中比较常见的一些Freemarker的数字表示及格式化的相关问题。这个对于我们来说其实还是蛮重要的!实际上我是参考了人家的官方文档!地址如下,大家有兴趣的可以去看看原文!

freemarker官方文档地址
————————————————
版权声明:本文为CSDN博主「henry-hacker」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wangmeng951011/article/details/70568311

原文地址:https://www.cnblogs.com/linus-tan/p/11375664.html