文字

abs

(PHP 4, PHP 5)

abs绝对值

说明

number abs ( mixed $number )

返回参数 number 的绝对值。

参数

number

要处理的数字值

返回值

number 的绝对值。 如果参数 number float ,则返回的类型也是 float ,否则返回 integer (因为 float 通常比 integer 有更大的取值范围)。

范例

Example #1 abs() 例子

<?php
$abs 
abs (- 4.2 );  // $abs = 4.2; (double/float)
$abs2  abs ( 5 );    // $abs2 = 5; (integer)
$abs3  abs (- 5 );   // $abs3 = 5; (integer)
?>

参见

  • gmp_abs() - Absolute value
  • gmp_sign() - Sign of number

用户评论:

[#1] alex.khimich.org [2013-10-17 07:58:22]

Few ways to convert values to negative
<?php

// Multiplying by "-1"
$v = -abs($v);

// Using ternary operator
$v $v <= $v : -$v;

?>

[#2] svein dot tjonndal at gmail dot com [2011-05-25 12:44:12]

If you don't have/want GMP and are working with large numbers/currencies:

<?php
function mb_abs($number)
{
  return 
str_replace('-','',$number);
}
?>


No need to worry about encoding, as your numbers should all be basic (ANSI) strings.

[#3] Ister [2008-07-17 01:59:19]

[*EDIT* by danbrown AT php DOT net: Merged user's corrected code with previous post content.]


jeremys indicated one thing - there is no sgn function wich actually seems a bit strange for me. Of course it is as simple as possible, but it is usefull and it is a standard math function needed occasionally.

Well, I have solved this function in a bit different matter:

<?php

function sgn($liczba)
{
    if(
$liczba>0)
        
$liczba=1;
    else if(
$liczba<0)
        
$liczba=-1;
    else if(!
is_numeric($liczba))
        
$liczba=null;
    else
        
$liczba=0;
    return 
$liczba;
}

?>


The difference is that it returns null when the argument isn't a number at all.

上一篇: 下一篇: