muyustan
muyustan

Reputation: 1585

Processing float() function

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.

Upvotes: 2

Views: 287

Answers (3)

knittl
knittl

Reputation: 265757

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.

Upvotes: 5

Martín Zaragoza
Martín Zaragoza

Reputation: 1817

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)

Upvotes: 1

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.

Upvotes: 1

Related Questions