First of all, is this function special to processing or does it exist in java by default?
When I code in processing the line below,
println(float("88") + "\t" + float("88\n") + "\t" + float("88p") ); // p is just an arbitrary character other than '\n'
It outputs
88.0 88.0 NaN
So, why float() function works fine with '\n' character but does not work with 'p' ? Aren't they both characters? I know '\n' is something special but in this case does it make a difference?
edit : I have replaced 'K' with 'p' because of some warnings came from the answers.
3 Answers 3
It exists only in processing. If you wanted a similar function in Java, there's Float#parseFloat(String)
I assume it works with \n, because that's a newline character which is whitespace. float likely trims whitespace before parsing the value. K is not a whitespace character and not a digit, so it cannot be parsed to a float.
8 Comments
k could have actual semantic meaning - if I saw 88k in print, I'd assume that they meant 88,000 (most likely 88,000ドル or 88,000 of some other unit of currency). With the specific case of k, it's not clear whether float should interpret it as 88 or 88,000.Presumably, it treats the \n as "meaningless filler" (i.e. it can be safely stripped off).
Also, in this context, k is not just an arbitrary character. 88k could be interpreted as 88,000, for example (which is not an all uncommon usage). Or, maybe that's not what you meant at all and the k was just a typo - either way, the framework doesn't know, so you're effectively asking it to read your mind here.
To give another example, consider a case like float("12abf456x"). What should the framework do with this? It's not at all clear how you could reasonably interpret that as a number with any certainty.
6 Comments
\n in the middle of the string (like float("8\n8"))? I assume that, in that case, it would throw an error.That specific float function exists in Processing
In java there's Float.parseFloat(s: String): float. This function shall yield NumberFormatExceptions when passing strings that cannot be recognised as proper floats.
\n is tipically treated as blank or whitespace. Strings are tipically trimmed before parsed (that is to say, whitespace and characters like \r and \n are removed from the beginning and end of said string). The K character is not removed, hence float() yields NaN (In Java you'd get a NumberFormatException)