开发者

What is the most direct way to reproduce this printf-like format with ColdFusion?

I've been thrown into ColdFusion for a very simple assignment. The application has some logic to display "help codes" (let's not get into what is a help code), however开发者_开发问答, the logic is buggy and needs to be fixed. Given a two-letters code, a 1-4 digits number, and another 1-2 digits number, I would need to display them like this printf call would:

printf("%s%04d%02d", letterCode, bigNumber, smallNumber);

If you're not familiar with the printf function, it accepts a format string (the first parameter), and writes the other variables in it according to the given format. %s means "write a string" and %d means "write a number"; %0zd means "write a number and pad it with zeroes so it's at least z characters long (so %04d means "write a number and pad it with zeroes so it lengths at least 4 digits).

Here are a few examples with %s%04d%02d:

"AD", 45, 12:  AD004512
"GI", 5121, 1: GI512101
"FO", 1, 0:    FO000100

However, it's my very first time with ColdFusion, and I couldn't find anything like printf or sprintf to format strings.

The other guy, who doesn't work here anymore, resorted to a (non-working) loop, and I thought it would be better to use library code instead of actually fixing the loop, since anyways I might need to do similar things again.


<cfset bigNumberPadded = NumberFormat(bigNumber,"0000")>
<cfset smallNumberPadded = NumberFormat(smallNumber,"00")>
<cfoutput>#letterCode##bigNumberPadded##smallNumberPadded#<cfoutput>

Or alternatively... as suggested by bpanulla, and corrected by Leigh

<cfset args = ["AD", javacast("int", 45), javacast("int", 12)]>
<cfset output= createObject("java","java.lang.String").format("%s%04d%02d", args) >


You can use NumberFormat to pad a number with leading zeros in CF.

<cfoutput>#letterCode##NumberFormat(bigNumber, '0000')##NumberFormat(smallNumber, '00')#</cfoutput>


There's lots of ways to do this in the Java layer underpinning ColdFusion. Here's one Java resource:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

Make instances of the Java classes you need with CFOBJECT or CreateObject.


I am assuming you are displaying these to a webpage? If so, I would use a switch/case statement. Since you said "given a two-letter code...", a switch/case would work well. For example:

<cfswitch expression="#twoLetterCode#">
    <cfcase value="aa12348">%s%04d%02d</cfcase>
    <cfcase value="bb23456">%s%05f%01e</cfcase>
    <cfcase value="cc97641">%s%08g%10j</cfcase>
    <cfdefaultcase>%s%04d%02d</cfdefaultcase>
</cfswitch>

Or you could use an if/else instead. But the main point (to answer your question) is that in ColdFusion you just type out the display characters (be it help codes, or text, or whatever). You don't need to use a special function to display text to the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜