Absolute value function

None know if exists a function/command that get the absolute value for a number?

Thanks:)

take the square root of the value multiplied by itself ...

sqrt(x^2)
sqrt(x*x)

Please mention:
What Operating System and version you have and what Shell or Programming Language you are using.
Please give an example, making it clear where the numbers are coming from and how they are stored. For example many Shells do not allow negative numbers in integer variables.
My understanding of "absolute value for a number" is its distance from zero.
The absolute value of 10 is 10.
The absolute value of -10 is 10.

If you are using the Korn shell, the majority of standard libm functions including abs() are available, e.g.

$ printf "%d\n"  $(( abs(-10) ))
10

The extended functions are only in ksh93 .

I'm using ksh with windows XP, but this is the result of the command :

$ printf "%d\n"  $(( abs(-10) ))
ksh: abs(-10) : unknown function

Try...

echo -10 | tr -d -
1 Like

Yes, it works!

I should use "expr ..." when i need make some calculations with the variable that memorizes the command output, but i think is good for my purpose.
Thanks.

Yes, it works! Thanks!!:slight_smile:

Thanks to everybody!

n=-10
echo "${n#-}"

What is the meaning fo the command: "n#-"? Does it change the sign the number or it only removes the char "-"

It removes only the characters -

 ${string#substring} Deletes shortest match of $substring from front of $string.

In a script where i need to create mathematical expressions, i would prefer a command that works on numbers changing the sign, it is probably more correct, but this solution can works too i think.

# n=-10
# expr match "$n" '-*\([0-9]*\)'
10