3

I don't want strings with newlines treated as numbers.

This should be considered a string

<cfscript>
  notes = "3
    ";
</cfscript>

The newline is preserved

 <cfoutput>
 <pre>|#notes#|</pre>    

 Number: #isNumeric(notes)# <!--- returns YES --->

 <pre>|#replacelist(notes, chr(10) , "\n") #|</pre>    

 Number: #isNumeric(notes)# <!--- returns YES
 </cfoutput>

Example on cffiddle

enter image description here

SOS
  • 6,430
  • 2
  • 11
  • 29
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
  • 3
    `isNumeric()` doesn't check to see if a `value` is `numeric`. It checks to see if a `string` can be converted to a `number`. And if trimming a value considered, then that would be `numeric`. Though I do agree that if there is a carriage return, it shouldn't be trimmed. :-/ – Shawn Apr 22 '19 at 18:38
  • 2
    If you need a TRUE `isINT()` look at Alex's answer here: https://stackoverflow.com/questions/46124664/best-way-to-check-if-value-is-integer-coldfusion-9 – Cory Fail Apr 22 '19 at 18:47
  • To make it even more fun, put a leading carriage return. – Shawn Apr 22 '19 at 19:06
  • Where is this an issue? You can always do `reFind('^\d+$', ... )` – Bernhard Döbler Apr 22 '19 at 21:12
  • Your example stretches what one might consider a good use case for this "feature", which goes back to the first versions of CF (circa 1995). Just remember that isNumeric() only tests whether or not a string can be used as a number. A typical use case is when forms are submitted, in which case each variable is always a string. When `form.foo == "2"`, you can pass that value into any function that expects a number and it will work. You never have to explicitly convert the string to a number. If you need a number, use `javaCast()` – Redtopia Apr 22 '19 at 21:30
  • @BernhardDöbler : That is the solution I am ending up using. You should write that up as an answer – James A Mohler Apr 22 '19 at 22:02

1 Answers1

1

I'm always hesitant to write an answer when I write from my head and have no written proof of what I'm saying. ColdFusion has various functions to validate data. There's isValid and isInteger and so forth. I'm not using these functions much because they validate values very liberally in some cases. For instance the Dollar sign will be accepted in some cases when there should be an integer value. I Therefore use regular expressions to check whether a value is numeric. reFind( "^\d+$", ... ) only allows digits. This expression allows an optional minus in front: reFind( "^-?\d+$", ... )

Bernhard Döbler
  • 1,960
  • 2
  • 25
  • 39