|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
hi guys,
is there a function that helps in calculating the absolute value of a number???? |
|
#2
|
|||
|
|||
|
Quote:
sure i think, you cannot use abs() so on cmd-line, try echo "your-number/1" |bc ![]()
__________________
working on Solaris[5-9], preferred languages french and C. |
|
#3
|
|||
|
|||
|
Quote:
I have tried 2/1 | bc and got, of course -2/1 | bc ksh: -2/1: not found which is not exactly what was required. If something is not ready made in the system, write it yourself, for instance: : # Function to evaluate the absolute value of a number abs () { # Check for numeric input if expr $1 + 0 2>/dev/null 1>&2 ; then # Is the number negative? if [ $1 -lt 0 ] ; then echo `expr 0 - $1` else echo $1 fi return 0 # OK else return 1 # Not a number fi } A=-10; abs $A || echo $A not a number A=121; abs $A || echo $A not a number A=1x1; abs $A || echo $A not a number This script was tested under Linux with bash, but it must work under ksh and sh, too. Have a fun ZL |
|
#4
|
|||
|
|||
|
try this as well:
Code:
echo "-.233" | awk ' { if($1>=0) { print $1} else {print $1*-1 }}'
|
|
#5
|
|||
|
|||
|
Quote:
i said echo "333.7777/1" | bc if you have a normal shell under a normal unix-os, you get 333 NOTA: BC and his brother DC, in unix, are known since 1978 Last edited by guggach : July 15th, 2005 at 03:44 PM. |
|
#6
|
|||
|
|||
|
Quote:
But guggach, have you ever heard what the absolute value is? You are presentig something what was not required, namely the integer part of a number. First read the question and then shoot. Regards ![]() |
|
#7
|
|||
|
|||
|
Quote:
Yes, awk is universal, but the question was to write a function. It is no problem for an experienced shell programmer to write some envelope to your statement to provide the required function. Regards ![]() |
|
#8
|
|||
|
|||
|
Quote:
ok, i did not check negative values ![]() my way remain BC val=-123.098 echo "a=$val/1;if(0>a)a*=-1;a"|bc |
![]() |
| Viewing: Dev Shed Forums > Operating Systems > UNIX Help > absolute value fuction in unix |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|