Is there a way of writing this logic in a single, elegant line of code?
<cfif ThumbnailWidth EQ 0>
<cfset Width = 75>
<cfelse>
<cfset Width = ThumbnailWidth>
</cfif>
Coldfusion 9:
<!--- Syntax: ((condition) ? trueStatement : falseStatement) --->
<cfset width = ((ThumbnailWidth EQ 0) ? 75 : ThumbnailWidth) />
Coldfusion 8 and below:
<!--- Syntax: IIf(condition, trueStatement, falseStatement) --->
<cfset width = IIf((ThumbnailWidth EQ 0), 75, ThumbnailWidth) />
Some will say that IIf() is to be avoided for performance reasons. In this simple case I'm sure you'll find no difference. Ben Nadel's Blog has more discussion on IIF() performance and the new ternary operator in CF 9.
I find your original elegant enough - tells the story, easy to read. But that's definitely a personal preference. Luckily there's always at least nine ways to do anything in CFML.
You can put that on one line (CFML has no end-of-line requirements):
<cfif ThumbnailWidth EQ 0><cfset Width = 75><cfelse><cfset Width = ThumbnailWidth></cfif>
You can also use IIF() Function - it'll do the trick:
<cfset Width = IIf(ThumbnailWidth EQ 0, 75, ThumbnailWidth)>
This construct is a little odd tho' - is more clear I think. The strength of IIF() is that it can also be used inline (it is a function after all). For example:
<img src="#ImageName#" width="#IIf(ThumbnailWidth EQ 0, 75, ThumbnailWidth)#">
This last form is often used to maintain a clean(er) HTML layout while injecting dynamic code.
Like Neil said, it's fine the way it is. If you really want a single line you could make it a cfscript with a ternary operator, like:
<cfscript>width = (ThumbnailWidth == 0) ? 75 : ThumbnailWidth;</cfscript>
Haven't tested this code, but it should work.
If you are looking for concise code, then you can take it a step further than the other examples, taking advantage of CF's evaluation of non-zero values as true:
<!--- CF 9 example --->
<cfset width = ThumbnailWidth ? ThumbnailWidth : 75>
<!--- CF 8 and below --->
<cfset width = iif(ThumbnailWidth, ThumbnailWidth, 0)>
Naturally, you'll sacrifice a little clarity, but that's the tradeoff for more compact code.
I personally prefer something more along the lines of this:
<cfscript>
Width = ThumbnailWidth;
if(NOT Val(Width)) // if the Width is zero, reset it to the default width.
Width = 75;
</cfscript>
Related
I have this working nicely in tag format, but am trying to migrate everything into cfscript. How can I do this one? (essentially, it loops over from date1 to date2, and needs to be in 15 minute intervals.
<cfset from=now()>
<cfset to=dateadd("d", 1, from)>
<cfloop from="#from#" to="#to#" index="i" step="#CreateTimeSpan(0,0,15,0)#">
...stuff...
<cfloop>
It's how to specify the step bit which is getting me..
#Jarede's answer certainly gives you a loop which performs the same iterations with the same values as your requirement, but it's not really equivalent to the tag version. This is the closest to your example:
from = now();
to = dateadd("d", 1, from);
step = CreateTimeSpan(0,0,15,0);
for (i=from; i <= to; i+=step){
// ... stuff ...
}
If you're incrementing (or decrementing) and index value, use a for() loop, If your condition is not based around an index value, use a do or a while loop.
As I mentioned in a comment above, if you are not familiar with CFScript, you need to be. I recommend reading this, thoroughly: CFScript. It's the only complete documentation of CFScript I'm aware of. If you notice any omissions... send me a pull request.
<cfscript>
variables.dtNow = now();
variables.dtTmrw = dateAdd('d',1,variables.dtNow);
do {
variables.dtNow = dateAdd('n',15,variables.dtNow);
writeOutput(variables.dtNow);
} while(variables.dtNow neq variables.dtTmrw);
</cfscript>
Got a critical error like: The value cannot be converted to a number. what can be the problem? Since i tried to write this values like:
1. <cfset ortalama=trim(val(db_maliyet_temp))+ds_toplam_maliyet>
2. <cfset ortalama=val(db_maliyet_temp)+ds_toplam_maliyet>
3. <cfset ortalama=db_maliyet_temp+ds_toplam_maliyet>
the first and second are just doesnt count the db_maliyet_temp,
and the 3 give out the error: The value cannot be converted to a number.
value for db_maliyet_temp: 2.806,71
for ds_toplam_maliyet: 394,22
These are not valid numbers. If you would like the total of the numbers, you can try this.
<cfset aryMaliyetNumbers = ListToArray(db_maliyet_temp, ",")>
<cfset aryToplamNumbers = ListToArray(ds_toplam_maliyet, ",")>
<cfset total = ArraySum(aryMaliyetNumbers) + ArraySum(aryToplamNumbers)>
There are several ways to skin this cat. This should at least get you going. Works perfectly on my CF 7 box!
EDIT
After the ridiculous amount of comments to clarify the question, I believe this is the solution.
<cfset db_maliyet_temp = Replace(Replace("2.806,71", ".", ""), ",", ".")>
<cfset ds_toplam_maliyet = Replace(Replace("394,22", ".", ""), ",", ".")>
<cfset total = db_maliyet_temp + ds_toplam_maliyet>
If you want the number without decimals, you can do this:
<cfset db_maliyet_temp = Replace(Replace("2.806,71", ".", ""), ",", ".")>
<cfset ds_toplam_maliyet = Replace(Replace("394,22", ".", ""), ",", ".")>
<cfset total = val(db_maliyet_temp + ds_toplam_maliyet)>
IMPORTANT
You have a much larger problem than a CF error. You need to fix the underlying issue that's causing your number to be formatted incorrectly.
This should do the trick:
<cfscript>
function convertToNumber(num){
return reReplace(reReplace(num,'.','','ALL'),',','.','ALL');
}
</cfscript>
<cfset ortalama=convertToNumber(db_maliyet_temp)+convertToNumber(ds_toplam_maliyet)>
Basically it just removes the '.' since that is formatting not needed for math and replaces the ',' with a decimal so that it can be treated as a number. This will only work if ALL the numbers you are going to be dealing with are formatted this way, if there are any formatted like 1,200.90 then you will have to be a little more fancy.
Have you tried the LSParseNumber() function?:
http://cfquickdocs.com/cf9/#lsparsenumber
Or the val() function?:
http://cfquickdocs.com/cf9/#val
Also, it may be easier to clean the data before it get's entered either with client-side validation (if it's coming from a form) or server-side validation.
How would I use use a string function to select everything in a variable after the last "/"
http://domain.com/g34/abctest.html
So in this case I would like to select "abctest.html"
Running ColdFusion 8.
Any suggestions?
Um, a bit strange to give very similar answer within few days, but ListLast looks as most compact and straightforward approach:
<cfset filename = ListLast("http://domain.com/g34/abctest.html","/") />
And yes, IMO you should start with this page before asking such questions on SO.
Joe I'd use the listToArray function, passing the "/" as the delimiter, get the length of the array and get the value in the last slot. See sample below
<cfset str = "http://domain.com/g34/abctest.html"/>
<cfset arr = ListToArray(str,"/","false")/>
<cfset val = arr[ArrayLen(arr)]/>
<cfoutput>#str# : #val#</cfoutput>
produces
http://domain.com/g34/abctest.html : abctest.html
ColdFusion's LSCurrencyFormat function appears to be using round-to-half-even (banker's rounding). Is there anyway to change this? I'd like to change it to standard round-half-up rounding that most people are taught in grade school.
An example:
LSCurrencyFormat(39.7340): $39.73
LSCurrencyFormat(39.7350): $39.74
LSCurrencyFormat(39.7360): $39.74
LSCurrencyFormat(39.7440): $39.74
LSCurrencyFormat(39.7450): $39.74 <== I want this to be $39.75
LSCurrencyFormat(39.7460): $39.75
I do not think there is a way to customize the rounding mode used by the numeric functions. (Though I could be wrong) You may have to dip into java for customized rounding behavior
Update My mistake. I thought the need was for something basic masks did not already provide. Oh, well. Maybe this example will be useful to someone anyway ..
Update Added HALF_UP rounding mode example
(Note: The Locale handling is quick and dirty. I am sure there is a more elegant way of doing it..)
<cfset Locale = createObject("java", "java.util.Locale")>
<cfset Mode = createObject("java", "java.math.RoundingMode")>
<cfset Formatter = createObject("java", "java.text.NumberFormat").getCurrencyInstance(Locale.US)>
<cfset Formatter.applyPattern("$######,######.####")>
<cfset input = LSParseNumber("39.735", "en_US")>
Input <cfoutput>#input#<br></cfoutput>
<cfset Formatter.setRoundingMode( Mode.HALF_EVEN )>
HALF_EVEN <cfoutput>#Formatter.format(input)#<br></cfoutput>
<cfset Formatter.setRoundingMode( Mode.HALF_DOWN )>
HALF_DOWN <cfoutput>#Formatter.format(input)#<br></cfoutput>
<cfset Formatter.setRoundingMode( Mode.HALF_UP )>
HALF_UP <cfoutput>#Formatter.format(input)#<br></cfoutput>
Try LSNumberFormat() with a mask
#LSNumberFormat(39.7350,"$_.__")# = $39.7350
Why not round before you send the value to the LSCurrencyFormat?
LSCurrencyFormat(yourRoundingFunction(39.7450))
Also see http://jamiekrug.com/blog/index.cfm/2009/2/12/ColdFusion-round-function-bug-when-operation-performed-on-argument
For example, I want just the "filename" of a file in a field. Say I have myimage.jpg I only want to display "myimage" How do I get just that?
Use the List functions to your advantage.
<cfset FileName = ListDeleteAt(FileFullName, ListLen(FileFullName, "."), ".")>
Be aware that this only works for file names that actually have a file extension (that is defined as the thing after the last dot). To make it safer, the following is better:
<cfset ExtensionIndex = ListLen(FileFullName, ".")>
<cfif ExtensionIndex gt 1>
<cfset FileExt = ListGetAt(ExtensionIndex , ".")>
<cfset FileName = ListDeleteAt(FileFullName, ExtensionIndex, ".")>
<cfelse>
<cfset FileExt = "">
<cfset FileName = FileFullName>
</cfif>
To complicate things a bit further: There may be files that start with a dot. There may be file names that contain many adjacent dots. List functions return wrong results for them, as they ignore empty list elements. There may also be files that have dots, but no extension. These can only be handled if you provide an extension white list: ListFindNoCase(FileExt, "doc,xls,ppt,jpg"). If you want to account for all of this, you probably need to resign to a reguar expression:
<cfset FileExtRe = "(?:\.(?:doc|xls|ppt|jpg))?$">
<cfset FileName = REReplaceNoCase(FileFullName, FileExtRe, "")>
To split file name from path, ColdFusion provides distinct functions that also handle platform differences: GetFileFromPath() and GetDirectoryFromPath()
Tomalak's answer is good, but this can get tricky. Given a file named "mydoc.ver1.doc" (a valid Windows file name) which is the filename and which is the extension? What if there is a filepath?
You can still leverage the list functions to your advantage, however, even in these scenarios.
You can easily parse out the file from the path with
fullFileName=listLast(fieldname,"\/")
If you assume the filename is everything before the dot, then
theFileName=listFirst(fullFileName,".")
will work.
If you want to ensure that you get everything but what's after the last period, then a little trickery is needed, but not much. There is not a listAllButLast() function (although such a thing might exist on CFLIB.org) but there are two ways I can think of to get what you're after.
fileName=reverse(listRest(reverse(fullFileName),"."))
or
fileName=listDeleteAt(fullFileName,listLen(fullFileName,"."),".")
As with Tomalak's suggestion, however, this will break down on a filename that lacks an extension. Wrapping this in a <cfif listLen(fullFileName,".") GT 1> will account for that.
The current accepted solution will not work for a file that does not contain an extension.
You can solve this by using a regular expression to strip the extension only if it exists:
<cfset FileName = rereplace( FullFileName , '\.[^.]+$' , '' ) />
This might still not be perfect - you might have a file that has a . but it isn't considered an extension - you can solve this either by using a list of known extensions to strip, or by limiting how long an extension you will accept (e.g. upto 5):
<cfset FileName = rereplace( FullFileName , '\.(jpg|png|gif|bmp)$' , '' ) />
<cfset FileName = rereplace( FullFileName , '\.[^.]{1,5}$' , '' ) />
So you first need to find the position of the last fullstop (there could be more than one fullstop in the full filename). I don't think Coldfusion has a find function that works backwards, so reverse the string first:
<cfset Position = Find(".", Reverse(FullFileName))>
If that returns zero then you don't have a fullstop in the file name, so handle appropriately. Else ...
<cfset Filename = Left(FullFileName, Len(FullFileName) - Position>
As of ColdFusion 9+ (perhaps earlier, but I can't verify), the Apache Commons library was included. Within that is org.apache.commons.io.FilenameUtils. You can utilize methods within the cut down on the amount of operations needed in CF to get the same (or similar) results.
filepath = "some/dir/archive.tar.gz";
oUtils = createObject("java", "org.apache.commons.io.FilenameUtils");
writeDump(oUtils.getFullPath(filepath)); // "some/dir/"
writeDump(oUtils.getName(filepath)); // "archive.tar.gz"
writeDump(oUtils.getBaseName(filepath)); // "archive.tar"
writeDump(oUtils.getExtension(filepath)); // "gz"
writeDump(oUtils.getPath(filepath)); // "some/dir/"
writeDump(oUtils.getPathNoEndSeparator(filepath)); // "some/dir"