|
Home > Archive > Unix Shell > November 2006 > convert character string to numeric
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
convert character string to numeric
|
|
| nicbone@gmail.com 2006-11-23, 1:16 pm |
| Apologies if this is 'obvious' question.
I have a character variable i.e. 10.1% that I have stripped the % off
using sed.
I now need to perform a calculation on the resulting string but because
it is still seen as a character variable I get the following error:-
value2=`expr $value + 1`
expr: non-numeric argument
so in a nutshell - how do i convert the character variable to a
numberic variable ?
Have had a good look around but cant figure it right now.
Thanks
Nick
| |
| Radoulov, Dimitre 2006-11-23, 1:16 pm |
|
<nicbone@gmail.com> wrote in message
news:1164289565.722420.274060@e3g2000cwe.googlegroups.com...
> Apologies if this is 'obvious' question.
>
> I have a character variable i.e. 10.1% that I have stripped the % off
> using sed.
>
> I now need to perform a calculation on the resulting string but because
> it is still seen as a character variable I get the following error:-
>
>
> value2=`expr $value + 1`
> expr: non-numeric argument
It's not about the type, it's because the value is not an integer:
$ var="10.1%"
$ expr ${var%\%} + 1
expr: non-numeric argument
$ var="10%"
$ expr ${var%\%} + 1
11
Use bc or awk for floating point arithmetic :
$ var="10.1%"
$ echo " ${var%\%} + 1" | bc -l
11.1
Regards
Dimitre
| |
| Chris F.A. Johnson 2006-11-23, 1:16 pm |
| On 2006-11-23, nicbone@gmail.com wrote:
> Apologies if this is 'obvious' question.
>
> I have a character variable i.e. 10.1% that I have stripped the % off
> using sed.
Why use sed? The shell parameter expansion (assuming a POSIX shell)
can do that:
value=10.1%
value=${value%\%}
> I now need to perform a calculation on the resulting string but because
> it is still seen as a character variable I get the following error:-
>
> value2=`expr $value + 1`
> expr: non-numeric argument
You cannot use decimal fractions with expr (and for integer
arithmetic, you don't need it).
> so in a nutshell - how do i convert the character variable to a
> numberic variable ?
To do calculations with decimal fractions, use awk or bc.
I use this function (it doesn't check that the expression you enter
is valid):
calc()
{
awk 'BEGIN { OFMT="%f"; print '"$*"'; exit}'
}
value2=`calc "$value + 1"`
> Have had a good look around but cant figure it right now.
--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
|
|
|
|
|