-3

I use this regular expression to check if input is float:

[+-]?([0-9]*[.])?[0-9]+

Can I use the same regular expression to check for double?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
smv
  • 19
  • 7
  • How do you think? What makes you think so? – Pshemo Sep 08 '17 at 11:28
  • 7
    When you have a look at a string, what's the difference between a float and a double? How would you as a human determine if the text represents a float value, a double value or something else? – Thomas Sep 08 '17 at 11:28
  • In short: No. @Thomas: You could probably go with counting decimal places, but that's... beside the point ( ͡° ͜ʖ ͡°) – Wep0n Sep 08 '17 at 11:31
  • @Thomas He means to check if it's either a float or a double. In other words `if(float || double) return true;`. – RaminS Sep 08 '17 at 11:32
  • Yes you can use the exactly same expression for a double. – Joop Eggen Sep 08 '17 at 11:32
  • 1
    @Gendarme but what do you mean by "a float or a double"? `Float.parseFloat` and `Double.parseFloat` accept arbitrarily-long inputs, and just discard what they can't represent. So sure, the same regex works for either. – Andy Turner Sep 08 '17 at 11:34
  • Well, he obviously just means double, and just didn't think his question through enough. – RaminS Sep 08 '17 at 11:36
  • @Wep0n that's what I was thinking of - you're right, that's not what the OP asked - but that's the only thing you can do to check for float _or_ double and my goal was to get him to that realization himself. – Thomas Sep 08 '17 at 11:43
  • 1
    @Gendarme yes that's what he asked but what would that mean? Besides the capacity and precision of the number (i.e. can it be represented by the datatype) or maybe some prefix/suffix like Java's `f` (which I doubt would be part of any reasonable input besides source code) there's no way to check for "float or double" on a string (and using a regex implies the number comes as a string). – Thomas Sep 08 '17 at 11:48

1 Answers1

0

First of all, your regular expression doesn't cover all variants of text representations of a float or double because they also come in scientific form, e.g. 1.2345E15, so you need to change your regex accordingly.

A short googling resulted in this answer on StackOverflow where a better regex is described to be [-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)? (I haven't tested it, though).

To your main question: You can't. There are float and double values that will result into the same text output. What exactly is the reason, why you need this? Personally I try to not use float or double at all due to it's inaccuracies anyway. Maybe there is a completely different solution for what you need.

Lothar
  • 5,323
  • 1
  • 11
  • 27