• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Detecting that a String represents a valid number

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello all,

My understanding is that we should never catch a Runtime exception,

I have the situation of parsing a String that represents a number (int)
almost every day..

How can I detect if the String represents a valid integer without using Integer.parseInt(String) and catch NumberFormatException ??

I'm using the following code:


Do you have a better technique (without catching NumberFormatException) ?
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
check out the API for java.lang.Character. There's lots of helpful methods there (in particular look for .isDigit() ).

Also, I'm moving this to the Intermediate forum, as its not an advanced question, so please continue the discussion there.
[ May 27, 2004: Message edited by: Jessica Sant ]
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Never catch runtimes, indeed. Generalizations are always wrong! (Including that one of course.)

I have no problem with your parseInt and catch. Throw is a bit expensive if you have lots of non-numbers, like reading a whole book and trying to find the numbers. Try is free if you never throw, so if your input is 99% good, it's probably not a worry.

It's easy to check for digits with character tests or regular expressions, but you also have to check ranges, signs, decimal points, etc. 3000000000 is all nice digits, but not a valid int.
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Catching a RuntimeException (or subclass of) is generally poor form, and even more so when exception handling is used for control flow (rather than the intentional "exceptional condition" handling).

One might go on to argue that NumberFormatException should have been a checked exception, and purists might consider wrapping it in some way to achieve such a mechanism.

In your case, you are violating the generalisations, but it is justified and there is no better way. If it bothers you that much, isolate it in one method called isParsableTo<T>, where <T> is the numeric type.

Also, suggestions that refer to the checking of each digit to be numerical are unfounded, since there are many occasions where a String will parse to a numeric type, that contain non-numerical characters:
Integer.parseInt("-23");
Double.parseDouble("1e4");

and many times that a String contains all digits yet still fails parsing:
Integer.parseInt("34634736352352352345234523452345324523452345345");

Good luck!
 
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

How can I detect if the String represents a valid integer without using Integer.parseInt(String) and catch NumberFormatException ??




Also, I'd disagree with Tony that, practically speaking, you need to check for


It's possible that you might get such a number, but I'm guessing it's not practically possible.

HTH,
M

[ May 27, 2004: Message edited by: Max Habibi ]
[ May 28, 2004: Message edited by: Max Habibi ]
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note that Max's suggested pattern will match "+0", but Integer.parseInt(String) will throw a NumberFormatException when trying to parse "+0".
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dirk is right, I was careless in my example. It's been adjusted, in case you actually need to use it.

M
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



It's possible that you might get such a number, but I'm guessing it's not practically possible.





What do you do in this case? Do you allow the user to enter a number that won't parse and fail miserably? Having worked in the field for a number of years, I am inclined to suggest that doing this kind of thing is a fundamental mistake on the developer's part. More importantly, it's never the user's fault - ALWAYS handle the fact that the user misuses your application (because it WILL happen) gracefully.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
it's never the user's fault

Well, I tend to think that usually it is the user's fault. But it's our responsibility to anticipate that, and report it clearly and gracefully. Otherwise someone may think it's our fault.

I agree with Tony, and with Stan. What's wrong with catching a NumberFormatException? Yeah, it's a RuntimeException. So what? Integer.parseInt() provides a nice well-defined mechanism for handling this sort of thing, and the alternatives presented thus far are iffy at best. That is, they will probably work, in most cases. But failing to consider what happens in the remaining cases is just asking for trouble, IMO. It's really easy to handle this problem with try/catch and Integer.parseInt() - don't let some silly generalized rula about not catching RuntimeExceptions get in your way.
[ May 31, 2004: Message edited by: Jim Yingst ]
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm willing to bet nickels to donuts that the application isn't reading information in from the command line, and that the extreme example given isn't likely at all to occur.

However, having said that, I can see where you might not feel good about the possibility that something might go wrong. As such, forget this nonsense about catching NumberFormatExceptions, and try the following pattern.

The rule of thumb is this. If it makes you feel icky, try to avoid it. Now the question you have to ask yourself is this: Does catching a RuntimeException make you feel icky?




Pop quiz: there's one number that's valid, but rejected here. What is it?

ps - is the regex clear, or should I step into it?
[ June 01, 2004: Message edited by: Max Habibi ]
 
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Max:
I guess there is a cut'n'paste-error, or I'm getting the whole thing wrong.
Your expression returns nearly allways 'false', except when the number starts with '2'.

a shameless NumberFormatExceptionsCatcher
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
cut & paste.

Try it now, give up your RuntimeException catching ways, and be forgiven.

M
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Stefan]: I guess there is a cut'n'paste-error

You may need to correct the line feed inserted into the regex. Try:

[Max]: Pop quiz: there's one number that's valid, but rejected here. What is it?

Quite a few more than one, I'm afraid. I'm guessing you're referring to -2147483648. But there are numerous others, such as 2099999999.

Here are a couple patterns that should work a bit better:

-?(?:\d{1,9}|(?:[0-1]\d{0,9}|2(?:[0-0]\d{0,8}|1(?:[0-3]\d{0,7}|4
(?:[0-6]\d{0,6}|7(?:[0-3]\d{0,5}|4(?:[0-7]\d{0,4}|8(?:[0-2]\d{0,3}|3
(?:[0-5]\d{0,2}|6(?:[0-3]\d{0,1}|4[0-7]))))))))))|-2147483648

or

(?:\d{1,9}|(?:[0-1]\d{0,9}|2(?:[0-0]\d{0,8}|1(?:[0-3]\d{0,7}|4
(?:[0-6]\d{0,6}|7(?:[0-3]\d{0,5}|4(?:[0-7]\d{0,4}|8(?:[0-2]\d{0,3}|3
(?:[0-5]\d{0,2}|6(?:[0-3]\d{0,1}|4[0-7]))))))))))
|-(?:\d{1,9}|(?:[0-1]\d{0,9}|2(?:[0-0]\d{0,8}|1(?:[0-3]\d{0,7}|4
(?:[0-6]\d{0,6}|7(?:[0-3]\d{0,5}|4(?:[0-7]\d{0,4}|8(?:[0-2]\d{0,3}|3
(?:[0-5]\d{0,2}|6(?:[0-3]\d{0,1}|4[0-8]))))))))))

(Remove the newlines, of course.)

Here's how I built them:

The generated patterns are hideously ugly, of course. But at least they work. (Or seem to, so far.)

Note that the c == '0' condition is never actually used in this code, but it would be if someone wanted a pattern for a number whose max contained a 0 in it.

The rule of thumb is this. If it makes you feel icky, try to avoid it.

Mmmm, good idea.

Now the question you have to ask yourself is this: Does catching a RuntimeException make you feel icky?

Not at all. Not for a particular well-defined exception that I know the cause of, like NumberFormatException. I'd be much less sanguine about catching a NullPointerException, or all RuntimeExceptions. (Other than for logging purposes of course.) But there is really no reason to avoid the NumberFormatException solution here. It's much easier, and much less error prone, as Max demonstrated.

Well, as Stan noted, there could be a reason to avoid the NFE, if indeed illegal values are fairly common, and performance of this method is a bottleneck. In that case, throwing and catching an exception may be too slow, and patterns may be a good fit. Then again - in most possible applications I can imagine, we'd want to not only find out if a string contains a legal int value, but also calculate what that int is. And the pattern solution doesn't provide any help there. So in that scenario it's probably more effective to loop through the string and calculate the int value as we go. If there's actually a performance bottleneck here.
[ June 01, 2004: Message edited by: Jim Yingst ]
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'd feel much different about the runtime exception if I let it out of the method. Since it's localized to a few lines of code I don't feel too bad.
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:
yucky code



pfft
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, Max, I thought we were eschewing the clean, simple solutions in this thread. (That's what I got from the first post, anyway.) Here's an alternate:

Still not as clear and simple as the original parseInt(), in my opinion, but oh well...
[ June 01, 2004: Message edited by: Jim Yingst ]
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jim,

You call compound statements in a conditional, assignment and equality tests on the same line, and compareTos on Strings that just happen to be numbers clear code? You'd better get back to finishing the SCJD, and toot sweet!

M

ps -it it your formatting or mine that's causing the weird wrapping here?
[ June 01, 2004: Message edited by: Max Habibi ]
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You call compound statements in a conditional, assignment and equality tests on the same line, and compareTos on Strings that just happen to be numbers clear code?

Sure. At least as clear as "num.replaceFirst("-?2(\\d{1,9})","$1")" to extract the last 9 digits. :roll: I could insert comments if you like, but that seems boring.

compound statements in a conditional

Yeah those ANDs and ORs are really confusing.

assignment and equality tests on the same line

This is why God gave us parentheses. (As one atheist to another, of course.)

compareTos on Strings that just happen to be numbers

Sorry, if I turn on the part of my brain that knows about Integer.parseInt() the proper solution becomes too blindingly obvious.

ps -it it your formatting or mine that's causing the weird wrapping here?

Dunno. Everything looks pretty normal to me, except that it looks like you're indenting with one space per level. Is that intentional? What do you see?
[ June 01, 2004: Message edited by: Jim Yingst ]
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:
You call compound statements in a conditional, assignment and equality tests on the same line, and compareTos on Strings that just happen to be numbers clear code?

Sure. At least as clear as "num.replaceFirst("-?2(\\d{1,9})","$1")" to extract the last 9 digits. :roll: I could insert comments if you like, but .

I like. People who don't comment code should be beaten on sight.

compound statements in a conditional

I'm sorry, I forgot that a simple || or && requires a new line.

It's ok: it seems that you're taking coding lessons from the same person who's teaching you spec-readin'.


Dunno. Everything looks pretty normal to me, except that it looks like you're indenting with one space per level. It that intentional? What do you see?

the one space is, but the entire topic seems skewed to me: like you might get with a long sentence. Are you using a wider screen? I'm on a 15' laptop.

M

ps - for simple Swing development, would you go with Eclipse or IDEA?

 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's ok: it seems that you're taking coding lessons from the same person who's teaching you spec-readin'.

Actually that comment just increases my certainty I'm in the right.

the entire topic seems skewed to me: like you might get with a long sentence. Are you using a wider screen? I'm on a 15' laptop.


Yeah, I'm on a larger screen, at home. I shrunk the browser and looked again - you're probably seeing what happens when one of the lines in a code block is longer than the width of your browser window. The horizontal scrollbar appears, and the margins get screwed up. I edited a few of my post which seemed to contain the longest lines, which should help a bit.

ps - for simple Swing development, would you go with Eclipse or IDEA?

Not sure. I don't do that much GUI stuff, and I don't trust auto code generation, so I've never really excercised those parts of either IDE. Generally I favor IDEA, but Eclipse is pretty close, IMO, and I wouldn't be surprised if it surpasses IDEA at some point. As far as Swing is concerned though, I'd kind of expect Eclipse to favor SWT over Swing. So at this point I'd probably go with IDEA, but that's not a very informed opionion really; just a guess. Hope that helps...
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You must unlearn what you have learned

[ June 01, 2004: Message edited by: Max Habibi ]
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You must unlearn what you have learned

I suppose the other part of the response to the try/catch solution with parseInt() would be: "There is no try. Only do."
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jim Yingst:
You must unlearn what you have learned

I suppose the other part of the response to the try/catch solution with parseInt() would be: "There is no try. Only do."




lol . That's pretty good.

M
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hmm, comparing strings 3 > 2999999999. Can't compare a candidate to the max & min until you've converted to int and then it's too late. I kinda like the "cheat" to convert to double first, but now how do you cheat to implement isDouble(String)? You'll run out of larger numeric types some day.

[ June 02, 2004: Message edited by: Stan James ]
[ June 02, 2004: Message edited by: Stan James ]
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hmm, comparing strings 3 > 2999999999.

So, can you find a sample input where this situation would actually arise?
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
but now how do you cheat to implement isDouble(String)? You'll run out of larger numeric types some day.

The problem occurs for longs as well. Double isn't always capable of implementing long values precisely. You could get around this though using BigInteger and BigDecimal, whose constructors should be able to handle all valid number formats.
 
Stefan Wagner
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Max Habibi:

Pop quiz: there's one number that's valid, but rejected here. What is it?




Well - I rearranged the quoting/ coding, to avoid the well-known editing-vulnerabilities when citing code...

Of course, I found the number:


and called it with:
java NumberTester -0000000007
Output:
num.matcher b: false
NumFormExCa b: true: -7

Unfortunately for
java NumberTester -0000000008
I get -8, but everybody knows, -0000000008 isn't a valid octal number

I didn't test the other funny regexes.

In future I will test it this way:
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I find it difficult to believe that everyone is suggesting a bigger "hack" than the alternative (declaring to catch java.lang.NumberFormatException).

If it really makes you squirm, wrap it in a checked exception, then wrap all the "parse*" methods in an adapter - or write an adapter that implements the "squirmish" behaviour in one place and provides a "nice" API to clients.
Example:


Still a hack, but nowhere near as hacky as the suggestions.
In general, do not declare to explicitly catch unchecked exceptions.
Note that the Java 2 core API is imperfect in hundreds of places - NumberFormatException being an unchecked exception is just one.
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I find it difficult to believe that everyone is suggesting a bigger "hack" than the alternative

Everyone? Not at all. I wholeheartedly support the parseInt / catch NumberFormatException solution. So does Stan, I gather. I'm just having fun exploring alternatives. Note that some of the silliness of code I've posted is intentional, given that I believe a natural and obvious solution has already been suggested (and inexplicably ruled out, in the very first post.) Eventually we saw an alternative that didn't make me laugh out loud in derision (namely, Max's latest solution using Double.parseDouble()). But it took a while, and still doesn't offer any real benefits over the original obvious solution. Perhaps this thread should be moved to Programming Diversions, since that's it's only real interest at this point, IMO.
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think it depends of how much it bothers you to step outside of architectural guidelines. For me, catching an unchecked exception in the scenario described just seems wacky.

I'm pretty sure that String.matches("-?1?\\d{1,9}") is sufficient as an alternative, but it seemed that a more 'perfect' answer was wanting: hence, the short method I posted, and Jim's little attempt.

let's focus a bit on what we're talking about here: one answer is


if (num.matches("-?\\d{1,10}"))
int x = (int)Double.parseDouble(num);


another is

int x = -1;
try
{
x = Integer.parseInt(num);
}
catch(NumberFormatException nfe)
{
nfe.printStackTrace();
}



to me, the former seems more clear and 'cleaner' than the latter: YMMV, of course.

And yes, you will have to forgive the 4 am solution I posted: I sometimes wonder if it shouldn't be illegal to code @ that hour.

All best,
M
[ June 03, 2004: Message edited by: Max Habibi ]
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Everyone? Not at all.



OK, I was exaggerating
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think it depends of how much it bothers you to step outside of architectural guidelines.

Well my feeling is that it's the authors of Integer.parseInt() (and all similar methods) who stepped outside of architectural guidelines, throwing an unchecked exception without providing any way to avoid it in the API. I'm just using their API in the simplest manner they've provided, and cleaning up afteer their mess.

to me, the former seems more clear and 'cleaner' than the latter: YMMV, of course.

Well, yeah. Why on earth would you want to print a stack trace in the latter scenario? And for some reason one method is returning a -1 in case of error, while the other is merely casting away any overflow error, without providing any way for the caller to know the overflow occurred. As I recall the question was how to detect whether a string represents a valid integer. I suppose it's easier to get a nice short method if you just ignore those pesky user requirements. :roll:
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jim, to your question about input that would cause 3 to compare ...

I haven't tried to play computer in huge detail here but given "3" wouldn't this get to "3".compareTo("2147....") and wouldn't "3" be bigger? Guess what I haven't check out is m.group(n) a String?
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

JY: Well, yeah. Why on earth would you want to print a stack trace in the latter scenario? And for some reason one method is returning a -1 in case of error,

Jim, old age and flashbacks must be brewing a powerful chemical soup in that brain of your: did you see a method, or did you see a snippet of code?

while the other is merely casting away any overflow error, without providing any way for the caller to know the overflow occurred. As I recall the question was how to detect whether a string represents a valid integer. I suppose it's easier to get a nice short method if you just ignore those pesky user requirements. :roll:

rolleyes indeed. You recall & read incorrectly, further substantiating my theory regarding your illicit usage of crack cocaine. Please read the question again, and this time, notice the original code.



Sincerely HTH,
M

ps - I'm still waiting for your feedback on my reserve polymorphism proposal.
[ June 04, 2004: Message edited by: Max Habibi ]
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Stan - the way the regex is written, group 2 will either be null, or it will have exactly ten characters in it (the first of which is [0-2]). If there are less than 10 digits, it matches the \\d{1,9}, and group 2 is null. If there are more than 10 digits, the expression doesn't match at all. I made sure I wouldn't be using compareTo() on Strings of different length.
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cool. I'd never seen the ?: syntax before. Hadda go look it up.
 
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Of course if you use Double.parseDouble you're still in trouble when the number is larger than a double can hold.
If you then cast the double to an int you're in trouble when it doesn't fit an int (though you may not find out until it's too late because it'll just loop back on itself presenting you with some incorrect value somewhere further down the line which will lead you to believe that that code is wrong and not your method to extract the int
 
Max Habibi
town drunk
( and author)
Posts: 4118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jeroen Wenting:
Of course if you use Double.parseDouble you're still in trouble when the number is larger than a double can hold.



This point(regarding a double) has already been raised and address(you'll need a proper method call). As for the wrapping: as already explained, a simple comparison between the int and double will tell you if the double has been truncated.

This has also already been addressed in previous posts.

M
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Jeroen]: Of course if you use Double.parseDouble you're still in trouble when the number is larger than a double can hold

Note that in Max's parseDouble() solution, parseDouble() is only invoked after using a regex to determine that the input is an integer of no more than ten digits. So there's no way it could be larger than a double can hold.
 
Stefan Wagner
Ranch Hand
Posts: 1923
Scala Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I prefer the NumberFormatException - test too.
The test via Double returns false too for -0000000008.

As long as nobody points me to an java-Integer-definition, which specifies, that -0000000008 is an invalid int, I would prefer to allow it too.
 
reply
    Bookmark Topic Watch Topic
  • New Topic