Convert a String to a Number


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Convert a String to a Number
# 1  
Old 03-17-2017
Convert a String to a Number

I read in two numbers from a user but the number is a string.
Code:
#!/bin/bash
read -p "Enter first number: " num1
read -p "Enter second number: " num2

I know you can use the the "expr" or "bc" command to automatically convert the string to a number then add them together. But I don't want to add these numbers, I just want to convert the string to a number. That's it. How would I go about doing this? thank you
# 2  
Old 03-17-2017
Hi Loc...

In shell scripting consider a number as a string of characters in _integer_ form only:-
Code:
Last login: Fri Mar 17 15:30:19 on ttys000
AMIGA:amiga~> number1="101"
AMIGA:amiga~> number2=57
AMIGA:amiga~> number3='8'
AMIGA:amiga~> echo "$(( number1 + number2 - number3 ))"
150
AMIGA:amiga~> _

If however you want to change the 'type' you will have to use something like python:-
Code:
Last login: Fri Mar 17 15:32:35 on ttys000
AMIGA:amiga~> python
Python 2.7.10 (default, Jul 30 2016, 19:40:32) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x="123"
>>> type(x)
<type 'str'>
>>> y=int(str(x))
>>> type(y)
<type 'int'>
>>> exit()
AMIGA:amiga~> _

# 3  
Old 03-17-2017
In bash use the typeset builtin (declare builtin does the same ). You declare the variable, THEN assign value to it:
Code:
typeset -i var=19

Once a variable is declared as a number it no longer will interpreted as a string, and allows some arithmetic operations.
From Typing variables: declare or typeset

Quote:
declare -i number
# The script will treat subsequent occurrences of "number" as an integer.

number=3
echo "Number = $number" # Number = 3

number=three
echo "Number = $number" # Number = 0
# Tries to evaluate the string "three" as an integer.

Certain arithmetic operations are permitted for declared integer variables without the need for expr or let.

n=6/3
echo "n = $n" # n = 6/3

declare -i n
n=6/3
echo "n = $n" # n = 2
# 4  
Old 03-17-2017
You need to be careful that you validate the input, else you can end up with this:-
Code:
$ typeset -i wally
$ wally=abc
$ echo $wally
0
$ wally=123abc456
bash: 123abc456: value too great for base (error token is "123abc456")
$

Perhaps you would be better to do something more like this after you read in num1 & num2:-
Code:
vnum1=$(tr -cd "[0-9]" < <(echo $num1))
if [ "$vnum1" != $"num1" ]
then
   echo "Invalid input!"
   exit
fi

It's a bit messy, but keeping it all as strings means that the shell doesn't care what the contents are. You can always for it to an integer afterwards should you wish.



I hope that this helps,
Robin
# 5  
Old 03-17-2017
Another way, a bit more shell independent (as long as it is Posix):
Code:
$ num=0001
$ echo "$num"
0001
$ echo "$((num+=0))"
1
$ echo "$num"
1


Last edited by Scrutinizer; 03-17-2017 at 07:09 PM..
# 6  
Old 03-17-2017
FWIW: a slightly better approach than
Code:
typeset -i

is simply to validate input
Example, pure bash validation of a number using bash regex where the variable is named n:
Code:
regex="^([0-9]$"
if [[ $n =~ $regex ]] ; then
  echo "$n is numeric"
else
  echo "$n is not numeric"
fi

# 7  
Old 03-17-2017
@jim, what if num=+1 or -001
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Concatenate a string and number and compare that with another string in awk script

I have below code inside my awk script if ( $0 ~ /SVC IN:/ ) { svc_in=substr( $0,23 , 3); if (msg_start == 1 && msg_end == 0) { msg_arr=$0; } } else if ( $0 ~ /^SVC OUT:/ ) { svc_out=substr( $0, 9, 3); if (msg_start == 1 && msg_end == 0) ... (6 Replies)
Discussion started by: bhagya123
6 Replies

2. Shell Programming and Scripting

Convert floating point to a number

Hello Guys, I have a floating point number 1.14475E+15 I want to convert this number in to full number (Integer or Big integer). I tried couple of functions it did not work. When I use INT=${FLOAT/.*} I am getting value as 1. I don't want a truncated value #!/bin/bash #... (9 Replies)
Discussion started by: skatpally
9 Replies

3. Shell Programming and Scripting

Convert string number to a integer

I have data as below "ROWS merge process complete. thousand rows changed" I need to get a variable assigned the value of 1000. I mean convert the string thousand to 1000. Any help or pointer. Please use CODE tags as required by forum rules! (6 Replies)
Discussion started by: dsravanam
6 Replies

4. Shell Programming and Scripting

Convert number

friends as I can convert this value to number in this example it is well but can vary the value does not help me cut from a nesecito espefifica opsiocn get zero CantCabe = 00023 Cant = 23 CantPntCabe = 0000000000000034 CantPnt = 34 if && ; then echo... (3 Replies)
Discussion started by: tricampeon81
3 Replies

5. Shell Programming and Scripting

How to convert number to english?

Hi gurus, I have a weird requirement. I need to convert the number to english lecture. I have 1.2 ....19 numbers I need to convert to first second third fourth, fifth, sixth... Is there any way convert it using unix command? thanks in advance. (8 Replies)
Discussion started by: ken6503
8 Replies

6. Shell Programming and Scripting

Search several string and convert into a single line for each search string using awk command AIX?.

I need to search the file using strings "Request Type" , " Request Method" , "Response Type" and by using result set find the xml tags and convert into a single line?. below are the scenarios. Cat test Nov 10, 2012 5:17:53 AM INFO: Request Type Line 1.... (5 Replies)
Discussion started by: laknar
5 Replies

7. Shell Programming and Scripting

changing number in bash (number is in form of string)

I have a txt file as database. when i run my program what it does is it ask me for 3 name and stored in the file as name1:name2:name3:1 when u enter 3 name it add those in file as above format and add 1 at the end. I what i want is if i enter same names again it changes that 1 to 2 and so... (3 Replies)
Discussion started by: Learnerabc
3 Replies

8. Shell Programming and Scripting

Convert e+ to number

Hi, I am using awk to get particular dates in seconds and the output am getting is like 1.28071e+09. How can I convert it to number format. Can anyone help me out? Thanks in advance..! (7 Replies)
Discussion started by: Kattoor
7 Replies

9. Shell Programming and Scripting

need script to convert number in hexadecimal

hi , i need a script to convert number into hexadecimal base for example: 237=>ED it s very important for me thank you in advance for you help (5 Replies)
Discussion started by: mips
5 Replies

10. Shell Programming and Scripting

Convert ip address to ip number

I want to make a script to read a list of ip addresses from a file then convert those ip addresses to ip number. ip number is made by removing the dots then transfer to a number , so the ip number transfered to binary then to decimal which will represents the ip number 0 : 4294967295 Also I... (17 Replies)
Discussion started by: moutaz1983
17 Replies
Login or Register to Ask a Question