Freemarker数字格式化总结

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

前言
咱们都知道,在咱们套页面的时候必定要注意的一点就是数字的展现,由于稍有不慎,你的页面上就可能出现0.60000000001这种的数字,若是是价格的话,那还真的是比较的尴尬!所以在咱们的代码层面咱们是必定须要作好相关的数字格式化的准备的,固然,这并不意味这在前端页面上咱们就能够不作任何事情!毕竟双重保险来的更加稳当一些。express

数字格式化
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…).ui

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

一、货币展现
        实际上咱们在平常的开发过程当中遇到的比较多的问题就是货币的展现,对于货币而言,在不一样的地区是有不一样的符号的。所以,freemarker为咱们提供了方便的方式实现。.net

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

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

二、百分数展现
        百分数也是咱们在平常的开发过程当中遇到的比较多的问题,其展现的方案以下。固然变量咱们依旧使用上面的变量。接口

${x?string.percent}ci

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

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

<#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

相关文章
相关标签/搜索