PHP Round function - round up to 2 dp? - php

In PHP how would i round up the value 22.04496 so that it becomes 22.05? It seems that
round(22.04496,2) = 22.04. Should it not be 22.05??
Thanks in advance

you can do it using ceil and multiplying and dividing by a power of 10.
echo ceil( 1.012345 * 1000)/1000;
1.013

Do not do multiplication inside a ceil, floor or round function! You'll get floating point errors and it can be extremely unpredictable. To avoid this do:
function ceiling($value, $precision = 0) {
$offset = 0.5;
if ($precision !== 0)
$offset /= pow(10, $precision);
$final = round($value + $offset, $precision, PHP_ROUND_HALF_DOWN);
return ($final == -0 ? 0 : $final);
}
For example ceiling(2.2200001, 2) will give 2.23.
Based on comments I've also added my floor function as this has similar problems:
function flooring($value, $precision = 0) {
$offset = -0.5;
if ($precision !== 0)
$offset /= pow(10, $precision);
$final = round($value + $offset, $precision, PHP_ROUND_HALF_UP);
return ($final == -0 ? 0 : $final);
}

The round function of PHP can handle an additional argument, which controls how the rounding is done: http://php.net/manual/en/function.round.php
Examples from the link:
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9

I think the best way:
echo ceil(round($value * 100)) / 100;
Example:
$value = 77.4;
echo ceil($value * 100) / 100; // 77.41 - WRONG!
echo ceil(round($value * 100)) / 100; // 77.4 - OK!

It's not working well.
round(1.211,2,PHP_ROUND_HALF_UP);
// Res: 1.21
My Solution:
$number = 1.211;
echo myCeil($number,2);
function myCeil($number,$precision = 0){
$pow = pow(10,$precision);
$res = (int)($number * $pow) / $pow;
if($number > $res){
$res += 1 / $pow;
}
return $res;
}
// Res 1.22

Why should it be 22.05? The third decimal is less than 5, hence when you round it to 2 decimal precision it's rounded down to 22.04

Related

PHP function to convert Hex to HSL (Not HSL to Hex)

Does anyone know how to convert a Hex color to HSL in PHP? I've searched but the functions that I’ve found don’t convert precisely the color.
I think the mistake in the second answer is using integer division rather than fmod() when calculating the hue when red is the maximum colour value $hue = (($green - $blue) / $delta) % 6;
I think the mistake in the first answer is in the saturation calculation -
for me $s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min); is a bit confusing to unpick
Since usually when I want to convert RGB to HSL I want to adjust the lightness value to make a lighter or darker version of the same colour, I have built that into the function below by adding an optional $ladj percent value.
The $hex parameter can be either a hex string (with or without the '#') or an array of RGB values (between 0 and 255)
The return value is an HSL string ready to drop straight in to a CSS colour. ie the values are from 0 to 359 for hue and 0 to 100% for saturation and lightness.
I think this works correctly (based on https://gist.github.com/brandonheyer/5254516)
function hex2hsl($RGB, $ladj = 0) {
//have we got an RGB array or a string of hex RGB values (assume it is valid!)
if (!is_array($RGB)) {
$hexstr = ltrim($RGB, '#');
if (strlen($hexstr) == 3) {
$hexstr = $hexstr[0] . $hexstr[0] . $hexstr[1] . $hexstr[1] . $hexstr[2] . $hexstr[2];
}
$R = hexdec($hexstr[0] . $hexstr[1]);
$G = hexdec($hexstr[2] . $hexstr[3]);
$B = hexdec($hexstr[4] . $hexstr[5]);
$RGB = array($R,$G,$B);
}
// scale the RGB values to 0 to 1 (percentages)
$r = $RGB[0]/255;
$g = $RGB[1]/255;
$b = $RGB[2]/255;
$max = max( $r, $g, $b );
$min = min( $r, $g, $b );
// lightness calculation. 0 to 1 value, scale to 0 to 100% at end
$l = ( $max + $min ) / 2;
// saturation calculation. Also 0 to 1, scale to percent at end.
$d = $max - $min;
if( $d == 0 ){
// achromatic (grey) so hue and saturation both zero
$h = $s = 0;
} else {
$s = $d / ( 1 - abs( (2 * $l) - 1 ) );
// hue (if not grey) This is being calculated directly in degrees (0 to 360)
switch( $max ){
case $r:
$h = 60 * fmod( ( ( $g - $b ) / $d ), 6 );
if ($b > $g) { //will have given a negative value for $h
$h += 360;
}
break;
case $g:
$h = 60 * ( ( $b - $r ) / $d + 2 );
break;
case $b:
$h = 60 * ( ( $r - $g ) / $d + 4 );
break;
} //end switch
} //end else
// make any lightness adjustment required
if ($ladj > 0) {
$l += (1 - $l) * $ladj/100;
} elseif ($ladj < 0) {
$l += $l * $ladj/100;
}
//put the values in an array and scale the saturation and lightness to be percentages
$hsl = array( round( $h), round( $s*100), round( $l*100) );
//we could return that, but lets build a CSS compatible string and return that instead
$hslstr = 'hsl('.$hsl[0].','.$hsl[1].'%,'.$hsl[2].'%)';
return $hslstr;
}
In real life I would break out the hex string to RGB array conversion and the percentage adjustment into separate functions, but have included them here for completeness.
You could also use the percent adjustment to shift the hue or saturation once you've got the colour in HSL format.
function hexToHsl($hex) {
$hex = array($hex[0].$hex[1], $hex[2].$hex[3], $hex[4].$hex[5]);
$rgb = array_map(function($part) {
return hexdec($part) / 255;
}, $hex);
$max = max($rgb);
$min = min($rgb);
$l = ($max + $min) / 2;
if ($max == $min) {
$h = $s = 0;
} else {
$diff = $max - $min;
$s = $l > 0.5 ? $diff / (2 - $max - $min) : $diff / ($max + $min);
switch($max) {
case $rgb[0]:
$h = ($rgb[1] - $rgb[2]) / $diff + ($rgb[1] < $rgb[2] ? 6 : 0);
break;
case $rgb[1]:
$h = ($rgb[2] - $rgb[0]) / $diff + 2;
break;
case $rgb[2]:
$h = ($rgb[0] - $rgb[1]) / $diff + 4;
break;
}
$h /= 6;
}
return array($h, $s, $l);
}
Rewritten (and adjusted a bit) from javascript from https://css-tricks.com/converting-color-spaces-in-javascript/
<?php
function hexToHsl($hex)
{
$red = hexdec(substr($hex, 0, 2)) / 255;
$green = hexdec(substr($hex, 2, 2)) / 255;
$blue = hexdec(substr($hex, 4, 2)) / 255;
$cmin = min($red, $green, $blue);
$cmax = max($red, $green, $blue);
$delta = $cmax - $cmin;
if ($delta === 0) {
$hue = 0;
} elseif ($cmax === $red) {
$hue = (($green - $blue) / $delta) % 6;
} elseif ($cmax === $green) {
$hue = ($blue - $red) / $delta + 2;
} else {
$hue = ($red - $green) / $delta + 4;
}
$hue = round($hue * 60);
if ($hue < 0) {
$hue += 360;
}
$lightness = (($cmax + $cmin) / 2) * 100;
$saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1))) * 100;
if ($saturation < 0) {
$saturation += 100;
}
$lightness = round($lightness);
$saturation = round($saturation);
return "hsl(${hue}, ${saturation}%, ${lightness}%)";
}
Example:
<?php
echo hexToHsl('fbffe0'); // outputs 'hsl(68, 100%, 94%)'

Get Percentage of 2 decimals

Seems simple but can't figure this out:
$goal = 10.000;
$actual = 55.32;
$percentChange = number_format(( $actual / $goal) * 100, 2);
echo $percentChange;
OUTPUT
553.20
WANTED OUTPUT
0.5532
The problem occurs only when output is less than 1 0.XXXX code is working fine from 1 above.
Remove the dot in $goal variable as is taking it as 10 with 4 decimals
Change this:
$goal = 10.000;
$actual = 55.32;
$percentChange = number_format(( $actual / $goal) * 100, 2);
echo $percentChange;
To this:
$goal = 10000;
$actual = 55.32;
$percentChange = number_format(( $actual / $goal) * 100, 4);
echo $percentChange;

How to calculate a certain color based on another color?

For example I have a blue color:
#049cd9 or rgba(4, 156, 218)
How can I calculate the correspondent color, which in this case it would be a dark blue color:
#004ea0 or rgba(0, 78, 160)
?
Normally I don't know the 2nd color (that I want to find out), so I want to find a way to get the darker color based on the first color.
Is there a formula or something that I can generate by substracting the two colors somehow?
So I've found HEX to HSL and HSL to HEX functions:
function hex_to_hue($hexcode)
{
$redhex = substr($hexcode,0,2);
$greenhex = substr($hexcode,2,2);
$bluehex = substr($hexcode,4,2);
// $var_r, $var_g and $var_b are the three decimal fractions to be input to our RGB-to-HSL conversion routine
$var_r = (hexdec($redhex)) / 255;
$var_g = (hexdec($greenhex)) / 255;
$var_b = (hexdec($bluehex)) / 255;
// Input is $var_r, $var_g and $var_b from above
// Output is HSL equivalent as $h, $s and $l — these are again expressed as fractions of 1, like the input values
$var_min = min($var_r,$var_g,$var_b);
$var_max = max($var_r,$var_g,$var_b);
$del_max = $var_max - $var_min;
$l = ($var_max + $var_min) / 2;
if ($del_max == 0) {
$h = 0;
$s = 0;
} else {
if ($l < 0.5) {
$s = $del_max / ($var_max + $var_min);
} else {
$s = $del_max / (2 - $var_max - $var_min);
}
;
$del_r = ((($var_max - $var_r) / 6) + ($del_max / 2)) / $del_max;
$del_g = ((($var_max - $var_g) / 6) + ($del_max / 2)) / $del_max;
$del_b = ((($var_max - $var_b) / 6) + ($del_max / 2)) / $del_max;
if ($var_r == $var_max) {
$h = $del_b - $del_g;
} else if ($var_g == $var_max) {
$h = (1 / 3) + $del_r - $del_b;
} else if ($var_b == $var_max) {
$h = (2 / 3) + $del_g - $del_r;
}
;
if ($h < 0) {
$h += 1;
}
;
if ($h > 1) {
$h -= 1;
}
;
}
;
return array($h, $s, $l);
/*
// Calculate the opposite hue, $h2
$h2 = $h + 0.5;
if ($h2 > 1)
{
$h2 -= 1;
};
return array($h2, $s, $l);
*/
}
function hue_to_hex($hue = array())
{
function hue_2_rgb($v1,$v2,$vh)
{
if ($vh < 0) {
$vh += 1;
}
;
if ($vh > 1) {
$vh -= 1;
}
;
if ((6 * $vh) < 1) {
return($v1 + ($v2 - $v1) * 6 * $vh);
}
;
if ((2 * $vh) < 1) {
return($v2);
}
;
if ((3 * $vh) < 2) {
return($v1 + ($v2 - $v1) * ((2 / 3 - $vh) * 6));
}
;
return($v1);
}
;
list($h2, $s, $l) = $hue;
// Input is HSL value of complementary colour, held in $h2, $s, $l as fractions of 1
// Output is RGB in normal 255 255 255 format, held in $r, $g, $b
// Hue is converted using function hue_2_rgb, shown at the end of this code
if ($s == 0) {
$r = $l * 255;
$g = $l * 255;
$b = $l * 255;
} else {
if ($l < 0.5) {
$var_2 = $l * (1 + $s);
} else {
$var_2 = ($l + $s) - ($s * $l);
}
;
$var_1 = 2 * $l - $var_2;
$r = 255 * hue_2_rgb($var_1,$var_2,$h2 + (1 / 3));
$g = 255 * hue_2_rgb($var_1,$var_2,$h2);
$b = 255 * hue_2_rgb($var_1,$var_2,$h2 - (1 / 3));
}
;
$rhex = sprintf("%02X",round($r));
$ghex = sprintf("%02X",round($g));
$bhex = sprintf("%02X",round($b));
return $rhex.$ghex.$bhex;
}
They work because I tested them by converting a color back and forth.
But I don't know how can I change the Hue and Luminosity properties just like in Photoshop?
The dark color would be H +13 and L -28.
And the hex_to_hsl function above returns float values between 0 and 1...
There are formulas that convert an RGB color to HSV (Hue, Saturation and Value). From the HSV you can change any of the HSV components and then convert back to RGB. I've found stuff online and done this before. Let me know if you want more details on the algorithms, I can dig them up for you if you want.
#XXXXXX represent hexa decimal number in colors for RED, GREEN and BLUE, each two characters from left to right if you increase the number it will get light, if decrease the number, it will be darker.
You need to convert the RGB value to HSL or HSV and then you can decrease the L (luma) or V (value) component as you wish and then convert back to RGB.
see this answer for example code:
RGB to HSV in PHP
The easiest way to tinker with how colours are perceived (ie, lighter, darker, brighter, duller, etc) is to convert it to HSL. There are plenty of resources online for converting RGB to HSL and back again in PHP and JavaScript. Google will find you as many implementations as you want. Then to decrease the lightness, reduce the L value (multiply by 0.75 or similar) and convert back to RGB.
function hex_to_hue($hexcode, $percent) {
$redhex = substr($hexcode, 0, 2);
$greenhex = substr($hexcode, 2, 2);
$bluehex = substr($hexcode, 4, 2);
// $var_r, $var_g and $var_b are the three decimal fractions to be input to our RGB-to-HSL conversion routine
$var_r = (hexdec($redhex)) / 255;
$var_g = (hexdec($greenhex)) / 255;
$var_b = (hexdec($bluehex)) / 255;
// Input is $var_r, $var_g and $var_b from above
// Output is HSL equivalent as $h, $s and $l — these are again expressed as fractions of 1, like the input values
$var_min = min($var_r, $var_g, $var_b);
$var_max = max($var_r, $var_g, $var_b);
$del_max = $var_max - $var_min;
$l = ($var_max + $var_min) / 2;
if ($del_max == 0) {
$h = 0;
$s = 0;
} else {
if ($l < 0.5) {
$s = $del_max / ($var_max + $var_min);
} else {
$s = $del_max / (2 - $var_max - $var_min);
}
;
$del_r = ((($var_max - $var_r) / 6) + ($del_max / 2)) / $del_max;
$del_g = ((($var_max - $var_g) / 6) + ($del_max / 2)) / $del_max;
$del_b = ((($var_max - $var_b) / 6) + ($del_max / 2)) / $del_max;
if ($var_r == $var_max) {
$h = $del_b - $del_g;
} else if ($var_g == $var_max) {
$h = (1 / 3) + $del_r - $del_b;
} else if ($var_b == $var_max) {
$h = (2 / 3) + $del_g - $del_r;
}
;
if ($h < 0) {
$h += 1;
}
;
if ($h > 1) {
$h -= 1;
}
;
}
;
//return array($h, $s, $l);
// Calculate the opposite hue, $h2
$h2 = $h + $percent;
if ($h2 > 1) {
$h2 -= 1;
}
// Calculate the opposite hue, $s2
$s2 = $s + $percent;
if ($s2 > 1) {
$s2 -= 1;
}
// Calculate the opposite hue, $s2
$l2 = $l + $percent;
if ($l2 > 1) {
$l2 -= 1;
}
return array($h2, $s2, $l2);
}

How do I make a lighter version of a colour using PHP?

Hello fellow earthlings. A quesion about RGB color and its usefulness in a simple tiny php code:
Imagine I have variable $colorA containning a valid six char color. say B1B100, a greenish natural color. Now If I would like to make a new color from that, which is, say, ten steps lighter thatn that original color, roughly.
$colorA = B1B100 // original color
php code with little color engine lightening stuff up goes here
$colorB = ?????? // original color lightened up
Is there a php ready function that KNOWS rgb colors something like
php function RGB ( input color, what to do, output color)
Where what to do could be +/- 255 values of brightness etc etc.
Is something like this already possible or am I day dreaming?
rgb-hsl($colorA, +10, $colorB);
If this does not exist, what would be the shortest code for doing this? Suggestions, code or ideas are all answers to me. Thanks.
This SO question has a full-blown PHP script that can convert a RGB to a HSL colour, and increase its H component of a HSL colour - it should be trivial to change to increase L instead.
In general if you want a lighter shade of a particular colour, the most accurate process is to convert from RGB to HSL (or HSV), change the 'L' (or 'V') value which represents lightness, and then convert back to RGB.
This will preserve the "hue", which represents where the colour sits on the spectrum, but change the "tint" (if lightening) or "shade" (if darkening) of that colour.
See http://en.wikipedia.org/wiki/HSL_and_HSV for more information.
On this website: http://www.sitepoint.com/forums/showthread.php?t=586223 they are talking about this code which is originally made by opensource Drupal. Seems to work fine in PHP!?
Now, how do I now indermingle myself with this code and change the lightness of an HSL value, before its outputted as RGB again?
<?php
### RGB >> HSL
function _color_rgb2hsl($rgb) {
$r = $rgb[0]; $g = $rgb[1]; $b = $rgb[2];
$min = min($r, min($g, $b)); $max = max($r, max($g, $b));
$delta = $max - $min; $l = ($min + $max) / 2; $s = 0;
if ($l > 0 && $l < 1) {
$s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
}
$h = 0;
if ($delta > 0) {
if ($max == $r && $max != $g) $h += ($g - $b) / $delta;
if ($max == $g && $max != $b) $h += (2 + ($b - $r) / $delta);
if ($max == $b && $max != $r) $h += (4 + ($r - $g) / $delta);
$h /= 6;
} return array($h, $s, $l);
}
### HSL >> RGB
function _color_hsl2rgb($hsl) {
$h = $hsl[0]; $s = $hsl[1]; $l = $hsl[2];
$m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l*$s;
$m1 = $l * 2 - $m2;
return array(_color_hue2rgb($m1, $m2, $h + 0.33333),
_color_hue2rgb($m1, $m2, $h),
_color_hue2rgb($m1, $m2, $h - 0.33333));
}
### Helper function for _color_hsl2rgb().
function _color_hue2rgb($m1, $m2, $h) {
$h = ($h < 0) ? $h + 1 : (($h > 1) ? $h - 1 : $h);
if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
if ($h * 2 < 1) return $m2;
if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (0.66666 - $h) * 6;
return $m1;
}
### Convert a hex color into an RGB triplet.
function _color_unpack($hex, $normalize = false) {
if (strlen($hex) == 4) {
$hex = $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];
} $c = hexdec($hex);
for ($i = 16; $i >= 0; $i -= 8) {
$out[] = (($c >> $i) & 0xFF) / ($normalize ? 255 : 1);
} return $out;
}
### Convert an RGB triplet to a hex color.
function _color_pack($rgb, $normalize = false) {
foreach ($rgb as $k => $v) {
$out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
}return '#'. str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
}
/* $testrgb = array(0.2,0.75,0.4); //RGB to start with
print_r($testrgb); */
print "Hex: ";
$testhex = "#b7b700";
print $testhex;
$testhex2rgb = _color_unpack($testhex,true);
print "<br />RGB: ";
var_dump($testhex2rgb);
print "<br />HSL color module: ";
$testrgb2hsl = _color_rgb2hsl($testhex2rgb); //Converteren naar HSL
var_dump($testrgb2hsl);
print "<br />RGB: ";
$testhsl2rgb = _color_hsl2rgb($testrgb2hsl); // En weer terug naar RGB
var_dump($testhsl2rgb);
print "<br />Hex: ";
$testrgb2hex = _color_pack($testhsl2rgb,true);
var_dump($testrgb2hex);
?>
PHP does have a couple image manipulation libraries. Either GD or Imagemagick
EDIT: I jumped the gun, these libraries do not have direct PHP color manipulation functions - I honestly assumed they did of a sort after seeing a lot of the things they can do with images via PHP. They do accomplish a lot of cool things. Here's one guy's example.

Rounding to the Nearest Ending Digits

I have the following function that rounds a number to the nearest number ending with the digits of $nearest, and I was wondering if there is a more elegant way of doing the same.
/**
* Rounds the number to the nearest digit(s).
*
* #param int $number
* #param int $nearest
* #return int
*/
function roundNearest($number, $nearest, $type = null)
{
$result = abs(intval($number));
$nearest = abs(intval($nearest));
if ($result <= $nearest)
{
$result = $nearest;
}
else
{
$ceil = $nearest - substr($result, strlen($result) - strlen($nearest));
$floor = $nearest - substr($result, strlen($result) - strlen($nearest)) - pow(10, strlen($nearest));
switch ($type)
{
case 'ceil':
$result += $ceil;
break;
case 'floor':
$result += $floor;
break;
default:
$result += (abs($ceil) <= abs($floor)) ? $ceil : $floor;
break;
}
}
if ($number < 0)
{
$result *= -1;
}
return $result;
}
Some examples:
roundNearest(86, 9); // 89
roundNearest(97, 9); // 99
roundNearest(97, 9, 'floor'); // 89
Thanks in advance!
PS: This question is not about rounding to the nearest multiple.
This works for me:
function roundToDigits($num, $suffix, $type = 'round') {
$pow = pow(10, floor(log($suffix, 10) + 1));
return $type(($num - $suffix) / $pow) * $pow + $suffix;
};
$type should be either "ceil", "floor", or "round"
I think this should work, and it's more elegant to me, at least:
function roundNearest($number, $nearest, $type = null)
{
if($number < 0)
return -roundNearest(-$number, $nearest, $type);
$nearest = abs($nearest);
if($number < $nearest)
return $nearest;
$len = strlen($nearest);
$pow = pow(10, $len);
$diff = $pow - $nearest;
if($type == 'ciel')
$adj = 0.5;
else if($type == 'floor')
$adj = -0.5;
else
$adj = 0;
return round(($number + $diff)/$pow + $adj)*$pow - $diff;
}
Edit: Added what I think you want from negative inputs.

Categories