开发者

Java: (int)(float)Float.valueOf(s) or Float.valueOf(s).toInt()

I just bumped into this little problem and I wanted the input of other people on this

I was wandering what was the best solution to convert a String to an int

(int)(float)Float.valueOf(s) 

or

Float.valueOf(s).toInt()

s is a String inputed from a textfield so I can not guarantee that it is necessarily an int

my instincts i开发者_StackOverflow社区s that the double cast is ugly and should be avoided

Your input?


Your requirements are unclear:

  • If you are expecting an integer and don't want to allow the user to enter a number with a decimal point in it, simply use Integer.valueOf(String) or Integer.parseInt(String) and catch the NumberFormatException.

  • If you want to allow numbers with decimal points, then use Float.valueOf(String) or Float.parseFloat(String).

    • If you simply want to truncate the float to an int then either Float.intValue() or two casts are equivalent. (The javadoc for intValue explicitly states this.)

    • If you want to round to the nearest int, use Math.round() instead of a cast.

You should catch NumberFormatException whatever approach you take, since the user could enter rubbish that is not a valid base-10 number (with or without a decimal point) ... or that exceeds the bounds of the number type.

(I suppose that you could use a regex or something to check the String before trying to convert it, but it is simpler to just let the exception happen and deal with it. The exception efficiency issue is unlikely to be a practical concern in this use-case.)


On your original question as to whether intValue() is better than two casts: it is a matter of style. The two approaches do the same thing ... according to the javadoc. It is possible that one will be slightly more efficient than the other, but:

  1. that shouldn't be a concern for your use-case, and
  2. the only way to know for sure would be to profile the two alternatives on your execution platform ... and frankly it is not worth the effort.


You should use Integer.valueOf(..), and catch the NumberFormatException (if the string cannot be parsed as an integer).


Integer.parseInt(string) would be best

int x = Integer.parseInt(s);

Would be best to check if the string is an int before calling this.


As others pointed out, its just matter of style not performance... but if you are worried about performance you should validate the text field data in browser itself by javascript using a regex

^[0-9]*$

which would allow only integers to be submitted to your back-end code and hence improving performance by avoiding one network trip. Still you should validate the data in back-end, for that you can use

Integer.parseInt(String s) throws NumberFormatException
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜