Freemarker number built-in function (value)

Source: Internet
Author: User
Tags abs html form numeric locale mongodb numeric value postgresql redis

Freemarker number formatting can be set in two places, one is global, that is, setting Number_format in the Freemarker.properties file, and the other is to use the string instruction to control the output format of the data. For example:

 

${num?string (' 0.00 ')}
if there are less than two digits after the decimal point, use 0 instead of

${num?string (' #.## ')}
if the decimal point is more than two bits, only two bits are left, otherwise the actual value
of the output The output is: 1239765.46

${num?string (', ###.00 ')}
output is: 1,239,765.46
integer portion per three bits, split, and guaranteed to retain two digits after the decimal point, less than 0 instead of

${num ? string (', ###.## ')}
output is: 1,239,765.46
integer part of every three bits, split, and after the decimal point extra two bits will only retain two bits, less than two digits to take the actual number of digits, you can not include the decimal point

${num? The output of string (' 000.00 ')}
is: 012.70
integer Part if less than three bits (000), preceded by 0 to complete, otherwise take the actual integer digit

${num?string (' ###.00 ')}
equivalent to
${num?string (' #.00 ')}
output is: 12.70
integer takes the actual number of digits

For more usage of the string directive, you can access the official documentation: Http://freemarker.sourceforge.net/docs/ref_builtins_number.html#ref_builtin_string_for_number





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

The output will be





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

First, using the built-in function C

Features: Regardless of the form of expression (such as "123,456.123,456", "123456.123456", "000123456.123456000", "123,456.123456", "1,2345,6.123456"), As long as the decimal separator is '. ' It can be converted into a computer-recognized string form, and all 123456.123456, when the computer is processed without the so-called thousand separators (spaces or commas), and the maximum number of digits that the computer supports is 16 digits behind the decimal point, and for now, it's enough for us to use. 

Usage: Suppose Strmun is a string-like number, you can write ${strnum?c}, such as ${"123,456.123,456"? C} with a value of 123456.123456 may be useful: for some forms allow users to enter numbers according to their own habits, Unified conversion at the time of submission



Second, use predefined number formats

There are four predefined number formats, namely computer (same as the built-in function C function), currency (currency format), number (numeric format), percent (percent) 

feature: the explicit meaning of these formats is localized (country) specified, are controlled by the Java Platform installation environment, not freemarker, so these functions are not recommended and are not flexible to use because of the default number format.



Third, use similar to Java in the form of a number format syntax

Features: For example, "0.#", the number on the left of the ' 0 ' represents the minimum number of digits for the integer part, and the number of the right ' # ' represents the maximum number of decimal places; for example, "# #0.0#" means that the thousand separator of the integer part is ', ', the fractional part retains a maximum of two bits, Expressed as a percentage, the fractional portion is up to two bits. 

Usage: Assuming that strnum is a number, you can write ${strnum?string (", # #0.0#")}, such as ${123456.123456?string (", # #0.0#")} with a value of 123,456.12 

Note: The number format is localized sensitive, but we usually set the default localization language for Freemarker, which is not a problem. May be useful: when the number format is suddenly used in a certain place, it is possible to call the string function, when it is necessary to use the number format in many places, so it is too cumbersome, you can consider setting the default number format form



Fourth, local settings

Features: If on a page, or a few pages (other pages can import into), the use of the number format is the same, you can consider the uniform configuration of the number format of the use: only need to use the format of the number before the setting can be, the format is as follows:< #settingnumber _format= ", # #0. # # > where", # #0. # # "is a syntax similar to the one in Java, which is the 3rd. 

Note: If you use a page, the entire page defaults to that format, unless you overwrite the default format with a string function, and, similarly, if you put it on a public page, the other pages will be the same format if they include it.



Fifth, global settings

Features: The formatted form usage of numbers is provided by default on all pages (for spring): 

Set its default number format in the Freemarker configuration file as follows: 

Copy code code as follows: 

<propertyname= " Freemarkersettings "> <props> ... <propkey=" Number_format ">0.##</prop> ... </props> </property> 

Sixth, rounding processing 

There are several rounding methods, namely round,floor,ceiling and string ("0") 

features: The first three kinds, literally well understood, we also often use, to say the last one, look at an example 1.5?string ("0") and 2.5?string ( The value of "0") is 2 as follows: 

in finance and statistics, rounding is based on the so-called half-principle, which means rounding the nearest "neighbor", unless the distance is equal to two neighbors, in which case it rounds to even-numbered neighbors. If you look at the rounding of 1.5 and 2.5, this is visible in the above example, and two are rounded to 2, because 2 is even, but 1 and 3 are odd. Usage: Suppose Strnum is a number, you can write ${strnum?round (floor/ceiling)} or ${strmun?string ("0")} 

Possible usage: Available in some cases where digital accuracy is not high (perhaps useful when paging), Some decimal-sensitive, or string functions 

such as: Copy code code as follows: 

${num?string (' 0.00 ')} If there are less than two digits after the decimal point, use 0 instead of the copy code code as follows: ${num?string (' #.## ')} If the decimal point is two bits extra, Only two bits are left, otherwise the output actuals output is: 

1239765.46 Copy the Code as follows: ${num?string (', ###.00 ')} output is: 1,239,765.46 

integer portion of every three bits used, split, and guaranteed to retain two digits after the decimal point, less than 0 instead of the copy generation Code codes are as follows: 

${num?string (', ###.## ')} output is: 1,239,765.46 

integer part of every three bits with, split, and two digits after the decimal point is only reserved two bits, less than two digits to take the actual number of digits, you can not include the decimal copy code code as follows: 

${num? String (' 000.00 ')} output is: 012.70 

integer part if less than three bits (000), preceded by 0, otherwise take the actual integer bit copy code code as follows:

${num?string (' ###.00 ')} is equivalent to the copy code code as follows: ${num? The output of string (' #.00 ')} is: 12.70 

freemarker The operation problem of digital formatting Freemarker in parsing the data format, automatically by default, the number is divided by 3 (1,000), this problem to the operation brought some additional processing complexity, 

There are several workarounds: 

1, in the template straightThe Add. toString () conversion number is a string, 

such as: Copy code code as follows: 

${languagelist.id.tostring ()}; 

2, in the Freemarker configuration file freemarker.properties and copy the code as follows : 

< #setting number_format= "#" > or < #setting number_format= "0" >; 

3, directly add < #setting number_format= "#" in the template > or < #setting number_format= "0", 

such as:< #if 

code as follows: Adminlanguagepaginationmsg?exists> < #setting number_format= "#" > 

For numeric formatting, the priority of numeric formatting can be set with STRNG and Number_format: 

The highest priority for the string, the lowest profile configuration, and the priority of the page setting in between.


Seventh. Summary

For numeric formatting, the priority of numeric formatting can be set with STRNG and Number_format: The highest priority for the string, the lowest priority for profile configuration, and the priority of the page setting in between.


Api:

Page Contents ABS C (when used as a numeric value) Is_infinite Is_nan lower_abc round, floor, ceiling string (when used as a numeric type) UPPER_ABC


Related FAQ: If there is something similar to 1,000,000 or 1 000 000 instead of 1000000, or 3.14 instead of 3,14, and vice versa, please refer to the relevant content in this and the FAQ here, and also note the built-in function C in the above content. 



ABS Note:

The built-in function exists from the Freemarker 2.3.20 version.

Gives the absolute value of the number. For example X?abs, if X is-5, it will get 5. 



C (when used as a numeric value) 

Note:

The built-in function exists from the Freemarker 2.3.3 version.


The built-in function converts the "computer language" number to a string, which is to the computer, not to the user. That is, it is formatted according to the use of the program language, which is independent of all local numeric formatting settings for Freemarker. It is usually used as a decimal separator, and it never uses a grouping delimiter (like 3,000,000), an exponential form (such as 5E20), an extra 0 (such as 03 or 1.0) at the beginning or end, and a + number (such as + 1). It prints 16 bits at most after the decimal point, so the absolute value of the value is less than 1E-16 and will be displayed as 0. The built-in function is very strict, as the default (like ${x}) number is converted to a string by a local (language, country) specific number format, which is for the user to see (for example, 3000000 may be printed as 3,000,000). When a number is not printed for a user (for example, for a database record ID, as part of a URL, or as a hidden field in an HTML form, or to print Css/javascript numeric text), the built-in function must be used to print a number (that is, using ${x?c} instead of ${x} ), otherwise the output may be corrupted due to the current number formatting, localized (for example, in some countries, where the decimal point is not a dot, but a comma) and a numeric value (such as a large number may be "corrupted" by the grouping delimiter).


If the Freemarker configuration setting entry is incompatible_imporvements to 2.3.21 (or higher), the built-in function will return "INF", "-inf", and "NaN" to the positive infinity/negative infinity and the IEEE non-floating-point number respectively. This is the XML Schema compatibility representation of these special values. (previously it would have returned the Java.text.DecimalFormat under US localization and was not understood by the arbitrary (universal) computer language.) )


Note that the built-in function also works on the Boolean value. 


Is_infinite 

Note:

The built-in function exists from the Freemarker 2.3.20 version.

Identifies whether the number is an infinite floating point (according to IEEE 754). For example, if the value based on Somenumber is infinite, the somenumber?is_infinite result is true or false, and of course, if the number is not a floating-point type, then false will be returned. 


Is_nan 

Note:

The built-in function exists from the Freemarker 2.3.20 version.



Identifies whether the number is a floating-point Nan (according to IEEE 754). For example, if the value based on Somenumber is NaN, the Somenumber?is_nan result is true or false, and of course, if the number is not a floating-point type, it will return false. 



LOWER_ABC 

Note:

The built-in function exists from the Freemarker 2.3.22 version.


Will 1, 2, 3, etc..., convert to String "a", "B", "C", etc... When "Z" is reached, it will continue to convert to "AA", "AB", etc... This has the same logic as the column labels for spreadsheet applications, such as Excel or Calc. The minimum value for the number is 1. There are no upper values. If the number is 0 or less, or if it is not an integer, then the template processing aborts and an error occurs.

For example:





< #list 1..30 as N>${N?LOWER_ABC} </#list >

Output:

Please refer to: upper_abc 


round, floor, ceiling 

Note:

The built-in function round from the Freemarker 2.3.13 version.


Convert a number to an integer using the determined rounding rule:

Round: Returns the most recent integer. If the number ends with. 5, then it carries the carry (that is, rounding in the positive infinity direction)

Floor: The integer that returns the number after the decimal is dropped (that is, the negative infinity is discarded)

Ceiling: Returns the integer (that is, positive infinity) after the decimal number is rounded

For example:





< #assign testlist=[
  0, 1,-1, 0.5, 1.5, -0.5,
  -1.5, 0.25, -0.25, 1.75, -1.75]>
< #list testlist as Res Ult>
    ${result}? Floor=${result?floor}? ceiling=${result?ceiling}? Round=${result?round}
</#list >

Output:





    0. floor=0 ceiling=0? round=0            
    1? floor=1? ceiling=1? round=1        
    -1? floor=-1? ceiling=-1? round=-1 0.5      
    ? floor= 0. ceiling=1 round=1 1.5? floor=1 ceiling=2? round=2 -0.5? floor=-1? ceiling=0? round=0     
    -1.5? floor=-2? Ceiling=-1 round=-1 0.25? floor=0 ceiling=1? round=0     
    -0.25? floor=-1 ceiling=0? round=0? 1.75? floor=1?    
    ceiling=2 round=2     
    -1.75? floor=-2 ceiling=-1? round=-2

These built-in functions may be useful for paging. If you just want to show the rounding of numbers, you should use the string built-in function or the Number_format setting. 


string (when used as a numeric type)

Converts a number to a string. It uses the default format that programmers set through Number_format and locale. You can also explicitly use this built-in function to specify a number format, which is shown later.

There are four predefined number formats: computer, Currency,number and percent. The explicit meaning of these formats is localized (country)-specified, controlled by the Java Platform installation environment, not freemarker, except computer, which is used as the same format as the C built-in function. You can use the predefined formats like this:





< #assign x=42>
${x}
${x?string}  <#--the same as ${x}--${x?string.number
}
${x? String.currency}
${x?string.percent}
${x?string.computer}

If you are US  locally, the output will be:





$42.00
4,200%
42

The output of the first three expressions is the same, because the first two expressions are the default format, and here is the "number". You can use a setting to change the default settings:





< #setting number_format= "Currency" >
< #assign x=42>
${x}
${x?string}  <#--the Same as ${x}--
${x?string.number}
${x?string.currency}
${x?string.percent}

The output will be:





$42.00
$42.00
$42.00
4,200%

Because the default number format is set to "currency".

In addition to these three predefined formats, you can also use any number format in the Java numeric format syntax:





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

The output will be:





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

Please note that in Freemarker, Foo.bar and foo["bar" are the same, and X?string.currency can also be written as x?string["currency", and of course not in practice. But in the above example, we have to use the square bracket syntax, because in syntax, the characters (numbers, dots, #) that are used are not allowed after the dot operator.

For historical reasons, you can also write the following code x?string ("0.#"), which is exactly the same as x?string["0.#".

In financial and statistical practice, rounding is based on the so-called half-principle, which means rounding the nearest "neighbor", unless the distance is equal to two neighbors, in which case it is rounded to even-numbered neighbors. If you look at the rounding of 1.5 and 2.5, this is visible in the above example, and two are rounded to 2, because 2 is even, but 1 and 3 are odd.

As in the pre-defined format shown earlier, the default format for numbers can be set in the template:





< #setting number_format= "0.##" >
${1.234}

The output will be:





1.23

Note that the number format is localized sensitive and localization settings work in formatting:





< #setting number_format= ", # #0. xx >
< #setting locale=" en_US ">
US people write:     ${12345678}
< #setting locale= "Hu" >
German people write: ${12345678}

The output will be:





US people write:     12,345,678.00
German People write:12.345.678,00

UPPER_ABC

Note:

The built-in function exists from the Freemarker 2.3.22 version.

Same as LOWER_ABC, but it is converted to uppercase letters, such as "A", "B", "C", ..., "AA", "AB", etc...

Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.