Strictly convert string to integer (or nil)
Use Integer(string)
It will raise an ArgumentError error if the string cannot convert to an integer.
Integer('5abc') #=> ArgumentError: invalid value for Integer(): "5abc"
Integer('5') #=> 5
You'd still need your number_or_nil method if you want the behavior to be that nil is returned when a string cannot be converted.
def number_or_nil(string)
Integer(string || '')
rescue ArgumentError
nil
end
You should be careful to rescue from a particular exception. A bare rescue (such as "rescue nil") will rescue from any error which inherits from StandardError and may interfere with the execution of your program in ways you don't expect. Integer() will raise an ArgumentError, so specify that.
If you'd rather not deal with exceptions and just prefer a shorter version of your number_or_nil you can take advantage of implicit return values and write it as:
def number_or_nil(string)
num = string.to_i
num if num.to_s == string
end
number_or_nil '5' #=> 5
number_or_nil '5abc' #=> nil
This will work the way you expect.
How remove an extra space in string and convert to int type?
here is a slightly better solution that would still allow you to have nil values
(please note that nil.to_i is 0 as well as any "text".to_i is also 0)
def my_method(str)
Integer(str.gsub(/\s/, ''))
rescue ArgumentError => e
nil
end
Example of use:
my_method('1000')
=> 1000
my_method('1 000')
=> 1000
my_method(' ')
=> nil
my_method('some_text')
=> nil
my_method('1.000')
=> nil
my_method('1,000')
=> nil
If you want to treat .
and ,
you can adapt the regex in gsub.
Ruby How to convert string to integer without .to_i
You can use Kernel::Integer:
Integer("219")
#=> 219
Integer("21cat9")
# ArgumentError: invalid value for Integer(): "21cat9"
Sometimes this method is used as follows:
def convert_to_i(str)
begin
Integer(str)
rescue ArgumentError
nil
end
end
convert_to_i("219")
#=> 219
convert_to_i("21cat9")
#=> nil
convert_to_i("1_234")
#=> 1234
convert_to_i(" 12 ")
#=> 12
convert_to_i("0b11011") # binary representation
#=> 27
convert_to_i("054") # octal representation
#=> 44
convert_to_i("0xC") # hexidecimal representation
#=> 12
Some use an "inline rescue" (though it is less selective, as it rescues all exceptions):
def convert_to_i(str)
Integer(str) rescue nil
end
There are similar Kernel methods to convert a string to a float or rational.
String to Double conversion nil in different region Swift
Careful handling of localized numeric strings
let inputString = "12,8"
let formatter = NumberFormatter()
formatter.locale = Locale.current // Locale(identifier: "de")
let number = formatter.number(from: inputString)
print(number) // 12.8
Cast variable to integer or null if not able to
Try this
$a = '1234';
$b = '3333';
$c = 'test';
list($a1, $b1, $c1) = array_map(function($elem) { return is_numeric($elem) ? intval($elem) : null; }, [$a, $b, $c]);
Result
print_r([$a1, $b1, $c1]);
Array
(
[0] => 1234
[1] => 3333
[2] =>
)
How to convert an integer in a base to a string
Numeric literals with a leading zero are considered to be octal (base 8) numbers.
The to_s
method converts the numbers to the default decimal (base 10).
- 21 octal is 17 decimal
- 11 octal is 9 decimal
For the expected results, remove the leading zeroes.
Swift: Determining if cast to integer from string succeeds
If 0
represents an error for you, you could do:
return Int(contents as String) ?? 0
??
is called the "nil coalescing operator". It returns the first value if it's not nil
, otherwise it returns the second value.
If you want more robust handling you could use guard
…
guard let value = Int(contents as String) else {
processError("Something went horribly wrong")
return 0
}
return value
Difference between Integer(value) and value.to_i
Integer(num)
will throw an ArgumentError
exception if num isn't a valid integer (you can specify the base).
num.to_i
will convert as much as it can.
For example:
"2hi".to_i
#=> 2
Integer("2hi")
#=> throws ArgumentError
"hi".to_i
#=> 0
Integer("hi")
#=> throws ArgumentError
"2.0".to_i
#=> 2
Integer("2.0")
#=> throws ArgumentError
Related Topics
How to Access Class Variables in Ruby 1.9
Using Gets() Gives "No Such File or Directory" Error When I Pass Arguments to My Script
Collectionproxy VS Associationrelation
Star Rating in Ajax with Ruby on Rails
Bundler Puts My Gems in My Project Directory
Get the Name of a Local Variable
Rails 3 Validates Inclusion of When Using a Find (How to Proc or Lambda)
How Are Array.Each and Array.Map Different
Remove "Www", "Http://" from String
Is Alias_Method_Chain Synonymous with Alias_Method
What Does the Underscore Mean in Literal Numbers
Vi Input Mode in Command Line Matlab
No Such File to Load Bundler Error for Rails 3
Ruby: "&& Return" VS "And Return"
Sudo Gem Install Pg Won't Work
In Ruby, How to I Control the Order in Which Test::Unit Tests Are Run