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
