Skip to content

Instantly share code, notes, and snippets.

@rizalp rizalp/PHP: Numbers
Created Apr 25, 2013

Embed
What would you like to do?
PHP: Numbers
<?php
// ensure that a string contains a number
if (is_numeric('five')) { /* false */ }
if (is_numeric(5)) { /* true */ }
if (is_numeric('5')) { /* true */ }
if (is_numeric(-5)) { /* true */ }
if (is_numeric('-5')) { /* true */ }
// is_numeric( ) properly parses decimal numbers, such as 5.1;
// however, numbers with thousands separators, such as 5,100, cause is_numeric( )
// to return false
if (is_numeric(str_replace($number, ',', ''))) {}
// Comparing Floating Point
// use a small delta value
// The size of your delta should be the smallest amount of difference you care about.
// Then use abs( ) to get the absolute value of the difference.
$delta = 0.00001;
$a = 1.00000001;
$b = 1.00000000;
if (abs($a - $b) < $delta) { /* $a and $b are equal */ }
// Rounding Number
$number = round(2.4); // $number = 2
$number = ceil(2.4); // $number = 3
$number = floor(2.4); // $number = 2
//carefull. it is undefined
$number = round(2.5); // $number is 2 or 3!
$delta = 0.0000001;
$number = round(2.5 + $delta); // $number = 3
// Random Number
// random number between $upper and $lower, inclusive
$random_number = mt_rand($lower, $upper);
mt_getrandmax(); //maximum random number
// Biased Random Numbers
// Some value appear more often
// returns the weighted randomly selected key
function pc_rand_weighted($numbers) {
$total = 0;
foreach ($numbers as $number => $weight) {
$total += $weight;
$distribution[$number] = $total;
}
$rand = mt_rand(0, $total - 1);
foreach ($distribution as $number => $weights) {
if ($rand < $weights) { return $number; }
}
}
$ads = array('ford' => 12234, // advertiser, remaining impressions
'att' => 33424,
'ibm' => 16823);
$ad = pc_rand_weighted($ads);
// Logarithm
// base e
$log = log(10); // 2.30258092994
// base 10
$log10 = log10(10); // 1
// other base
$log2 = log(10, 2); // 3.3219280948874
// Exponent
// raise e to power
$exp = exp(2); // 7.3890560989307
$exp = pow( 2, M_E); // 6.5808859910179
$pow = pow( 2, 10); // 1024
$pow = pow( 2, -2); // 0.25
$pow = pow( 2, 2.5); // 5.6568542494924
$pow = pow(-2, 10); // 1024
$pow = pow( 2, -2); // 0.25
$pow = pow(-2, -2.5); // NAN (Error: Not a Number)
// Format Number Output
number_format( )
$number = 1234.56;
print number_format($number); // 1,235 because number is rounded up
print number_format($number, 2); // 1,234.56
// TRIGONOMETRY
// assume radian
$cos = cos(2.1232);
$atan = atan(1.2);
// in degree
deg2rad( );
rad2deg( );
$cosine = rad2deg(cos(deg2rad($degree)));
// Convert Base
// works for all bases from 2 to 36 inclusive
$hex = 'a1'; // hexadecimal number (base 16)
$decimal = base_convert($hex, 16, 10); // $decimal is now 161
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.