Rectangle 27 351

Python method to check if a string is a float:

def isfloat(value):
  try:
    float(value)
    return True
  except:
    return False
isConvertibleToFloat(value)
val                   isfloat(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexidecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u''                  False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

convertibleToFloat

First of all this does not actually answer the question (wonder why people up-votes such answers). Second it assumes that the reader was surprised by the results, which need not be the case and from that assumption conclude that the reader is not as good as he thinks. It's rude to call people bad, it's worse when it's done on incorrect premises.

@skyking Your second point answers the first. The reason why it's been upvoted is because assuming people didn't know was spot on.

@skyking it was a TF2 joke, quoting the character called Heavy. The joke sailed so far over your head that you misinterpreted the detail on this work of art as a blemish when it fact it was the masterstroke. I marvel at how people can enjoy a free ride to mars and yet still moan bitterly about the inadequacy of the cup holders. You don't like it? Fine, show me how to do it better.

@skyring I up-voted the answer because it is an excellent summary of when python can parse strings into floats, and answers OP's more open-ended title question rather than his specific example. It serves the community of programmers well (which I think is the purpose of this website).

python - Parse String to Float or Int - Stack Overflow

python string parsing floating-point integer
Rectangle 27 347

Python method to check if a string is a float:

def isfloat(value):
  try:
    float(value)
    return True
  except:
    return False
isConvertibleToFloat(value)
val                   isfloat(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexidecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u''                  False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

convertibleToFloat

First of all this does not actually answer the question (wonder why people up-votes such answers). Second it assumes that the reader was surprised by the results, which need not be the case and from that assumption conclude that the reader is not as good as he thinks. It's rude to call people bad, it's worse when it's done on incorrect premises.

@skyking Your second point answers the first. The reason why it's been upvoted is because assuming people didn't know was spot on.

@skyking it was a TF2 joke, quoting the character called Heavy. The joke sailed so far over your head that you misinterpreted the detail on this work of art as a blemish when it fact it was the masterstroke. I marvel at how people can enjoy a free ride to mars and yet still moan bitterly about the inadequacy of the cup holders. You don't like it? Fine, show me how to do it better.

@skyring I up-voted the answer because it is an excellent summary of when python can parse strings into floats, and answers OP's more open-ended title question rather than his specific example. It serves the community of programmers well (which I think is the purpose of this website).

python - Parse String to Float or Int - Stack Overflow

python string parsing floating-point integer
Rectangle 27 1226

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
isdigit()

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

Nor does it work for numbers with decimal places like 1.2

That's a negative on negatives as well

@DanielGoldberg: I think you need to go lookup the definition of "digit"

python - How do I check if a string is a number (float)? - Stack Overf...

python casting floating-point type-conversion
Rectangle 27 1226

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
isdigit()

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

Nor does it work for numbers with decimal places like 1.2

That's a negative on negatives as well

@DanielGoldberg: I think you need to go lookup the definition of "digit"

python - How do I check if a string is a number (float)? - Stack Overf...

python casting floating-point type-conversion
Rectangle 27 1224

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
isdigit()

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

Nor does it work for numbers with decimal places like 1.2

That's a negative on negatives as well

@DanielGoldberg: I think you need to go lookup the definition of "digit"

python - How do I check if a string is a number (float)? - Stack Overf...

python casting floating-point type-conversion
Rectangle 27 12

Here's is my version. It checks against both positive and negative values lists, raising an exception for unknown values. And it does not receive a string, but any type should do.

def to_bool(value):
    """
       Converts 'something' to boolean. Raises exception for invalid formats
           Possible True  values: 1, True, "1", "TRue", "yes", "y", "t"
           Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
    """
    if str(value).lower() in ("yes", "y", "true",  "t", "1"): return True
    if str(value).lower() in ("no",  "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
    raise Exception('Invalid value for boolean conversion: ' + str(value))
>>> to_bool(True)
True
>>> to_bool("tRUe")
True
>>> to_bool("1")
True
>>> to_bool(1)
True
>>> to_bool(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: 2
>>> to_bool([])
False
>>> to_bool({})
False
>>> to_bool(None)
False
>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: Wasssaaaaa
>>>

One could get bitten by this: to_bool(["hello"]) which should be a perfectly valid call, if [] is supported

Returns "Exception: Invalid value for boolean conversion: ['hello']", which is expected and documented. In my opinion an empty list was clearly a false, but ['false'] wasn't clearly anything, so I left it out intentionally - that's a feature not a bug. Should be easy to add support for returning true for non-empty lists if that's what you want.

shure you documented it. But in real live one would never call to_bool([]). Instead he would do something along these lines: myList=someFunctionThatReturnAList `if (is_bool(myList)):... so one have a list and want to know if this list is None or empty.

Why not try this: >>> def a2b(arg): ... default = bool(arg) ... if isinstance(arg, str): ... return arg.lower() in ['true', 't', 'yes', 'y', '1'] ... else: ... return default

Minor point: you should probably prefer ValueError over a plain Exception.

Converting from a string to boolean in Python? - Stack Overflow

python string
Rectangle 27 12

Here's is my version. It checks against both positive and negative values lists, raising an exception for unknown values. And it does not receive a string, but any type should do.

def to_bool(value):
    """
       Converts 'something' to boolean. Raises exception for invalid formats
           Possible True  values: 1, True, "1", "TRue", "yes", "y", "t"
           Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
    """
    if str(value).lower() in ("yes", "y", "true",  "t", "1"): return True
    if str(value).lower() in ("no",  "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
    raise Exception('Invalid value for boolean conversion: ' + str(value))
>>> to_bool(True)
True
>>> to_bool("tRUe")
True
>>> to_bool("1")
True
>>> to_bool(1)
True
>>> to_bool(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: 2
>>> to_bool([])
False
>>> to_bool({})
False
>>> to_bool(None)
False
>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: Wasssaaaaa
>>>

One could get bitten by this: to_bool(["hello"]) which should be a perfectly valid call, if [] is supported

Returns "Exception: Invalid value for boolean conversion: ['hello']", which is expected and documented. In my opinion an empty list was clearly a false, but ['false'] wasn't clearly anything, so I left it out intentionally - that's a feature not a bug. Should be easy to add support for returning true for non-empty lists if that's what you want.

shure you documented it. But in real live one would never call to_bool([]). Instead he would do something along these lines: myList=someFunctionThatReturnAList `if (is_bool(myList)):... so one have a list and want to know if this list is None or empty.

Why not try this: >>> def a2b(arg): ... default = bool(arg) ... if isinstance(arg, str): ... return arg.lower() in ['true', 't', 'yes', 'y', '1'] ... else: ... return default

Minor point: you should probably prefer ValueError over a plain Exception.

Converting from a string to boolean in Python? - Stack Overflow

python string
Rectangle 27 12

Here's is my version. It checks against both positive and negative values lists, raising an exception for unknown values. And it does not receive a string, but any type should do.

def to_bool(value):
    """
       Converts 'something' to boolean. Raises exception for invalid formats
           Possible True  values: 1, True, "1", "TRue", "yes", "y", "t"
           Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
    """
    if str(value).lower() in ("yes", "y", "true",  "t", "1"): return True
    if str(value).lower() in ("no",  "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
    raise Exception('Invalid value for boolean conversion: ' + str(value))
>>> to_bool(True)
True
>>> to_bool("tRUe")
True
>>> to_bool("1")
True
>>> to_bool(1)
True
>>> to_bool(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: 2
>>> to_bool([])
False
>>> to_bool({})
False
>>> to_bool(None)
False
>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: Wasssaaaaa
>>>

One could get bitten by this: to_bool(["hello"]) which should be a perfectly valid call, if [] is supported

Returns "Exception: Invalid value for boolean conversion: ['hello']", which is expected and documented. In my opinion an empty list was clearly a false, but ['false'] wasn't clearly anything, so I left it out intentionally - that's a feature not a bug. Should be easy to add support for returning true for non-empty lists if that's what you want.

shure you documented it. But in real live one would never call to_bool([]). Instead he would do something along these lines: myList=someFunctionThatReturnAList `if (is_bool(myList)):... so one have a list and want to know if this list is None or empty.

Why not try this: >>> def a2b(arg): ... default = bool(arg) ... if isinstance(arg, str): ... return arg.lower() in ['true', 't', 'yes', 'y', '1'] ... else: ... return default

Minor point: you should probably prefer ValueError over a plain Exception.

Converting from a string to boolean in Python? - Stack Overflow

python string
Rectangle 27 13

This will check if all chars are digits (will be true only for not negative integers)

inputString.All(c => IsDigit(c));

You can also try regular expression

string pattern = "^[-+]?[0-9]*\.?[0-9]*$";
Regex.IsMatch(inputString, pattern)

I like this. It always bugged me to use an out variable when I just need a bool. This converted to the following code for me: if(productId.All(Char.IsDigit)). I like the elegance Itay.

The first example will fail if inputString is empty.

inputString.All(char.IsDigit);

c# - How to check whether a string in .NET is a number or not? - Stack...

c# string
Rectangle 27 13

This will check if all chars are digits (will be true only for not negative integers)

inputString.All(c => IsDigit(c));

You can also try regular expression

string pattern = "^[-+]?[0-9]*\.?[0-9]*$";
Regex.IsMatch(inputString, pattern)

I like this. It always bugged me to use an out variable when I just need a bool. This converted to the following code for me: if(productId.All(Char.IsDigit)). I like the elegance Itay.

The first example will fail if inputString is empty.

inputString.All(char.IsDigit);

c# - How to check whether a string in .NET is a number or not? - Stack...

c# string
Rectangle 27 684

array.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});
array.sort(function(o1,o2){
  if (sort_o1_before_o2)    return -1;
  else if(sort_o1_after_o2) return  1;
  else                      return  0;
});
array.sort(function(o1,o2){
  return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});

Define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays :

(function(){
  if (typeof Object.defineProperty === 'function'){
    try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
  }
  if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;

  function sb(f){
    for (var i=this.length;i;){
      var o = this[--i];
      this[i] = [].concat(f.call(o,o,i),o);
    }
    this.sort(function(a,b){
      for (var i=0,len=a.length;i<len;++i){
        if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
      }
      return 0;
    });
    for (var i=this.length;i;){
      this[--i]=this[i][this[i].length-1];
    }
    return this;
  }
})();

If your date is not directly comparable, make a comparable date out of it, e.g.

array.sortBy(function(o){ return new Date( o.date ) });

You can also use this to sort by multiple criteria if you return an array of values:

// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };

Is there no way to use the sort function already build in, in this manner as opposed to prototype?

@ryandlf I've added a short section showing how to use that directly for this case.

I accepted this any simply because its more complete and offers multiple solutions. @qw3n posted a perfectly acceptable answer as well.

@Phrogz when you want a String descending ordered, sortBy does not work, because - minus operator tries to convert the string to number, producing a NaN value. I wrote a new sortBy method inspired by your Schwartzian transform implementation, in order to overcome that issue. https://gist.github.com/jherax. Any suggestion from you is welcome.

datetime - Sort Javascript Object Array By Date - Stack Overflow

javascript datetime
Rectangle 27 63

public static int strToInt( String str ){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    //Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;
    }

    //Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
    }

    if (isNeg)
        num = -num;
    return num;
}

What if the input is greater than 2^32? What if the input contains non-numeric characters?

One of the things a programmer must learn on joining the workforce, if not before, is never to re-invent wheels. This may be a fun exercise, but don't expect your code to pass code review if you do this kind of thing in a commercial setting.

@yohm those are special case; you can handle with long and some regex; however, by then you can use parseInt.

-1 Sorry, but this is a pretty poor algorithm, with lots of limitations, no error handling, and some weird anomalies (eg "" gives an exception, "-" will produce 0, and "+" produces -5). Why would anyone choose this over Integer.parseInt(s)? - I see the point about this being an interview question, but a) that doesn't imply you'd do it this way (which is what the questioner asked), and b) this answer's a pretty bad example anyway.

How to convert a String to an int in Java? - Stack Overflow

java string int type-conversion
Rectangle 27 63

public static int strToInt( String str ){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    //Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;
    }

    //Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
    }

    if (isNeg)
        num = -num;
    return num;
}

What if the input is greater than 2^32? What if the input contains non-numeric characters?

One of the things a programmer must learn on joining the workforce, if not before, is never to re-invent wheels. This may be a fun exercise, but don't expect your code to pass code review if you do this kind of thing in a commercial setting.

@yohm those are special case; you can handle with long and some regex; however, by then you can use parseInt.

-1 Sorry, but this is a pretty poor algorithm, with lots of limitations, no error handling, and some weird anomalies (eg "" gives an exception, "-" will produce 0, and "+" produces -5). Why would anyone choose this over Integer.parseInt(s)? - I see the point about this being an interview question, but a) that doesn't imply you'd do it this way (which is what the questioner asked), and b) this answer's a pretty bad example anyway.

How to convert a String to an int in Java? - Stack Overflow

java string int type-conversion
Rectangle 27 6

Assuming your data is composed like in your example, you can try this:

[nums, directions] = textread('test.txt', '%d%s'); %# Read data from file
signs = ones(size(directions));                    %# Assume signs are positive
signs(strcmp(directions, 'S')) = -1;               %# Replace 'S' with negatives
result = nums(:) .* signs(:)                       %# Calculate result

Thanks a lot. It's working.

string - Conversion to Integer with Positive or Negative - Stack Overf...

string matlab
Rectangle 27 382

with positive integers you could use .isdigit:

>>> '16'.isdigit()
True

it doesn't work with negative integers though. suppose you could try the following:

>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True

it won't work with '16.0' format, which is similar to int casting in this sense.

def check_int(s):
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()

You have to test for BOTH cases: lambda s: s.isdigit() or (s.startswith('-') and s[1:].isdigit())

@Roberto: of course you should! and I'm sure you're capable of doing so!

note: u''.isdigit() is true but int(u'') raises ValueError. Use u.isdecimal() instead. str.isdigit() is locale-dependent on Python 2.

This seems important and convoluted enough to warrant a built-in really....

Python: Check if a string represents an int, Without using Try/Except?...

python string integer
Rectangle 27 2

In your case it is enough to simply check whether the input can be converted to a float in a try/except block. The conversion will be successful for any string that could have been converted to an integer as well.

How to check if string is (int or float) in Python 2.7 - Stack Overflo...

python string floating-point int
Rectangle 27 96

use str.split("\n", -1) (with a negative limit argument). When split is given zero or no limit argument it discards trailing empty fields, and when it's given a positive limit argument it limits the number of fields to that number, but a negative limit means to allow any number of fields and not discard trailing empty fields. This is documented here and the behavior is taken from Perl.

Java: String split(): I want it to include the empty strings at the en...

java string split
Rectangle 27 96

use str.split("\n", -1) (with a negative limit argument). When split is given zero or no limit argument it discards trailing empty fields, and when it's given a positive limit argument it limits the number of fields to that number, but a negative limit means to allow any number of fields and not discard trailing empty fields. This is documented here and the behavior is taken from Perl.

Java: String split(): I want it to include the empty strings at the en...

java string split
Rectangle 27 3

Admittedly, my solution wouldn't work for negative integers, but it will extract all positive integers from input text containing integers. It makes use of numeric_only locale:

int main() {
        int num;
        std::cin.imbue(std::locale(std::locale(), new numeric_only()));
        while ( std::cin >> num)
             std::cout << num << std::endl;
        return 0;
}
the format (-5) or (25) etc... some text.. and then.. 7987...78hjh.hhjg9878
5
25
7987
78
9878

The class numeric_only is defined as:

struct numeric_only: std::ctype<char> 
{
    numeric_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask> 
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
        return &rc[0];
    }
};

Convert string to int C++ - Stack Overflow

c++ string int
Rectangle 27 3

Admittedly, my solution wouldn't work for negative integers, but it will extract all positive integers from input text containing integers. It makes use of numeric_only locale:

int main() {
        int num;
        std::cin.imbue(std::locale(std::locale(), new numeric_only()));
        while ( std::cin >> num)
             std::cout << num << std::endl;
        return 0;
}
the format (-5) or (25) etc... some text.. and then.. 7987...78hjh.hhjg9878
5
25
7987
78
9878

The class numeric_only is defined as:

struct numeric_only: std::ctype<char> 
{
    numeric_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask> 
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
        return &rc[0];
    }
};

Convert string to int C++ - Stack Overflow

c++ string formatting int