Note that there are some explanatory texts on larger screens.

plurals
  1. PODetermine if a String is a number and convert in Java?
    text
    copied!<p>I know variants of this question have been asked frequently before (see <a href="https://stackoverflow.com/questions/1163615/java-library-to-check-whether-a-string-contains-a-number-without-exceptions">here</a> and <a href="https://stackoverflow.com/questions/1097332/convert-a-string-to-number-java">here</a> for instance), but this is <strong>not</strong> an <strong>exact</strong> duplicate of those.</p> <p>I would like to check if a <code>String</code> is a number, and if so I would like to store it as a <code>double</code>. There are several ways to do this, but all of them seem inappropriate for my purposes.</p> <p>One solution would be to use <code>Double.parseDouble(s)</code> or similarly <code>new BigDecimal(s)</code>. However, those solutions don't work if there are commas present (so "1,234" would cause an exception). I could of course strip out all commas before using these techniques, but that would seem to pose loads of problems in other locales.</p> <p>I looked at Apache Commons <code>NumberUtils.isNumber(s)</code>, but that suffers from the same comma issue.</p> <p>I considered <code>NumberFormat</code> or <code>DecimalFormat</code>, but those seemed far too lenient. For instance, "1A" is formatted to "1" instead of indicating that it's not a number. Furthermore, something like "127.0.0.1" will be counted as the number 127 instead of indicating that it's not a number.</p> <p>I feel like my requirements aren't so exotic that I'm the first to do this, but none of the solutions does exactly what I need. I suppose even I don't know <strong>exactly</strong> what I need (otherwise I could write my own parser), but I know the above solutions do not work for the reasons indicated. Does any solution exist, or do I need to figure out precisely what I need and write my own code for it?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload