PHP random decimal between two decimals with step 0.5 - php

I want to create random number between two decimal numbers with step 0.5.
Examples: 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, ...
Use PHP To Generate Random Decimal Beteween Two Decimals
So far I can generate numbers between 0 and 5 with one decimal comma.
How to integrate step 0.5?
$min = 0;
$max = 5;
$number = mt_rand ($min * 10, $max * 10) / 10;

This should work for you:
$min = 0;
$max = 5;
echo $number = mt_rand($min * 2, $max * 2) / 2;

Another possible way:
function decimalRand($iMin, $iMax, $fSteps = 0.5)
{
$a = range($iMin, $iMax, $fSteps);
return $a[mt_rand(0, count($a)-1)];
}

More intuitive, less unnecessary actions:
$min = 0;
$max = 5;
$step = 0.5;
// Simple for the case above.
echo $number = mt_rand($min * 2, $max * 2) * $step;
More general, a bit sophisticated case
echo $number = mt_rand(floor($min / $step), floor($max / $step)) * $step;
mt_rand offical docs just in case.

Related

Not the outcome i need... round of floor? [duplicate]

I want a php function which returns 55 when calling it with 52.
I've tried the round() function:
echo round(94, -1); // 90
It returns 90 but I want 95.
Thanks.
This can be accomplished in a number of ways, depending on your preferred rounding convention:
1. Round to the next multiple of 5, exclude the current number
Behaviour: 50 outputs 55, 52 outputs 55
function roundUpToAny($n,$x=5) {
return round(($n+$x/2)/$x)*$x;
}
2. Round to the nearest multiple of 5, include the current number
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 50
function roundUpToAny($n,$x=5) {
return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x;
}
3. Round up to an integer, then to the nearest multiple of 5
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 55
function roundUpToAny($n,$x=5) {
return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
}
Divide by 5
round() (or ceil() if you want to round up always)
Multiply by 5.
The value 5 (the resolution / granularity) can be anything — replaced it in both step 1 and 3
So in summary:
$rounded_number = ceil( $initial_number / 5 ) * 5
Round down:
$x = floor($x/5) * 5;
Round up:
$x = ceil($x/5) * 5;
Round to closest (up or down):
$x = round($x/5) * 5;
echo $value - ($value % 5);
I know it's an old question, but IMHO using modulus operator is the best way, and far more elegant than the accepted answer.
Try this little function I wrote.
function ceilFive($number) {
$div = floor($number / 5);
$mod = $number % 5;
If ($mod > 0) $add = 5;
Else $add = 0;
return $div * 5 + $add;
}
echo ceilFive(52);
From Gears library
MathType::roundStep(50, 5); // 50
MathType::roundStep(52, 5); // 50
MathType::roundStep(53, 5); // 55
MathType::floorStep(50, 5); // 50
MathType::floorStep(52, 5); // 50
MathType::floorStep(53, 5); // 50
MathType::ceilStep(50, 5); // 50
MathType::ceilStep(52, 5); // 55
MathType::ceilStep(53, 5); // 55
Source:
public static function roundStep($value, int $step = 1)
{
return round($value / $step) * $step;
}
public static function floorStep($value, int $step = 1)
{
return floor($value / $step) * $step;
}
public static function ceilStep($value, int $step = 1)
{
return ceil($value / $step) * $step;
}
Multiply by 2, round to -1, divide by 2.
Here is my version of Musthafa's function. This one is more complex but it has support for Float numbers as well as Integers. The number to be rounded can also be in a string.
/**
* #desc This function will round up a number to the nearest rounding number specified.
* #param $n (Integer || Float) Required -> The original number. Ex. $n = 5.7;
* #param $x (Integer) Optional -> The nearest number to round up to. The default value is 5. Ex. $x = 3;
* #return (Integer) The original number rounded up to the nearest rounding number.
*/
function rounduptoany ($n, $x = 5) {
//If the original number is an integer and is a multiple of
//the "nearest rounding number", return it without change.
if ((intval($n) == $n) && (!is_float(intval($n) / $x))) {
return intval($n);
}
//If the original number is a float or if this integer is
//not a multiple of the "nearest rounding number", do the
//rounding up.
else {
return round(($n + $x / 2) / $x) * $x;
}
}
I tried the functions from Knight, Musthafa and even the suggestion from Praesagus. They don't have support for Float numbers and the solutions from Musthafa's & Praesagus do not work correctly in some numbers. Try the following test numbers and do the comparison yourself:
$x= 5;
$n= 200; // D = 200 K = 200 M = 200 P = 205
$n= 205; // D = 205 K = 205 M = 205 P = 210
$n= 200.50; // D = 205 K = 200 M = 200.5 P = 205.5
$n= '210.50'; // D = 215 K = 210 M = 210.5 P = 215.5
$n= 201; // D = 205 K = 205 M = 200 P = 205
$n= 202; // D = 205 K = 205 M = 200 P = 205
$n= 203; // D = 205 K = 205 M = 205 P = 205
** D = DrupalFever K = Knight M = Musthafa P = Praesagus
I do it like this:
private function roundUpToAny(int $n, $x = 9)
{
return (floor($n / 10) * 10) + $x;
}
Tests:
assert($this->roundUpToAny(0, 9) == 9);
assert($this->roundUpToAny(1, 9) == 9);
assert($this->roundUpToAny(2, 9) == 9);
assert($this->roundUpToAny(3, 9) == 9);
assert($this->roundUpToAny(4, 9) == 9);
assert($this->roundUpToAny(5, 9) == 9);
assert($this->roundUpToAny(6, 9) == 9);
assert($this->roundUpToAny(7, 9) == 9);
assert($this->roundUpToAny(8, 9) == 9);
assert($this->roundUpToAny(9, 9) == 9);
assert($this->roundUpToAny(10, 9) == 19);
assert($this->roundUpToAny(11, 9) == 19);
assert($this->roundUpToAny(12, 9) == 19);
assert($this->roundUpToAny(13, 9) == 19);
assert($this->roundUpToAny(14, 9) == 19);
assert($this->roundUpToAny(15, 9) == 19);
assert($this->roundUpToAny(16, 9) == 19);
assert($this->roundUpToAny(17, 9) == 19);
assert($this->roundUpToAny(18, 9) == 19);
assert($this->roundUpToAny(19, 9) == 19);
function round_up($n, $x = 5) {
$rem = $n % $x;
if ($rem < 3)
return $n - $rem;
else
return $n - $rem + $x;
}
I just wrote this function in 20 min, based on many results I found here and there, I don't know why it works or how it works!! :D
I was mainly interested in converting currency numbers from this 151431.1 LBP to 150000.0 LBP. (151431.1 LBP == ~100 USD) which works perfectly so far, however I tried to make it somehow compatible with other currencies and numbers, but not sure if it works fine!!
/**
* Example:
* Input = 151431.1 >> return = 150000.0
* Input = 17204.13 >> return = 17000.0
* Input = 2358.533 >> return = 2350.0
* Input = 129.2421 >> return = 125.0
* Input = 12.16434 >> return = 10.0
*
* #param $value
* #param int $modBase
*
* #return float
*/
private function currenciesBeautifier($value, int $modBase = 5)
{
// round the value to the nearest
$roundedValue = round($value);
// count the number of digits before the dot
$count = strlen((int)str_replace('.', '', $roundedValue));
// remove 3 to get how many zeros to add the mod base
$numberOfZeros = $count - 3;
// add the zeros to the mod base
$mod = str_pad($modBase, $numberOfZeros + 1, '0', STR_PAD_RIGHT);
// do the magic
return $roundedValue - ($roundedValue % $mod);
}
Feel free to modify it and fix it if there's anything wrong
Probably you can also consider this one liner. It's faster! Works for $num >= 0 and $factor > 0.
$num = 52;
$factor = 55;
$roundedNum = $num + $factor - 1 - ($num + $factor - 1) % $factor;

Round up decimal number for specific decimal places in PHP

I want to round up my variable if it's decimal larger than .3 and if it's lower or equal it will round down, for example if i have 1.34 it will round up to 2, if i have 1.29 it will round down to 1, and if i have 1.3 it will round down to 1. I don't know how to do this precisely, right now i'm using the round basic function like this:
$weight = $weight/1000;
if($weight < 1) $weight = 1;
else $weight = round($weight, 0, PHP_ROUND_HALF_DOWN);
If you manipulate the numbers a bit, you can figure out if the decimals are .3 or higher. You achieve this by flooring the value, and subtract that from the original value. Check if the result of that, multiplied by 10, is greater than 3. If it is, you've got something above x.3.
$number = 1.31;
$int = floor($number);
$float = $number-$int;
if ($float*10 > 3.1)
$result = ceil($number);
else
$result = $int;
echo $result; // 2
Live demo
I made you a little hack, here's the code
$weight = 5088;
$weight = $weight/1000;
if($weight < 1) {
$weight = 1;
} else {
// I get the last number (I treat the $weight as a string here)
$last_number = substr($weight, -1, 1);
// Then I get the precision (floating numbers)
$precision = strlen(substr(strrchr($weight, "."), 1));
// Then I convert it to a string so I can use some helpful string functions
$weight_str = (string) $weight;
// If the last number is less then 3
if ($last_number > 3)
// I change it to 9 I could just change it to 5 and it would work
// because round will round up if then number is 5 or greater
$weight_str[strlen($weight_str) -1] = 9;
}
}
// Then the round will round up if it's 9 or round down if it's 3 or less
$weight = round($weight_str, $precision);
echo $weight;
Maybe something like this function?
function roundImproved($value, $decimalBreakPart = 0.3) {
$whole = floor($value);
$decimal = $value - $whole;
$decimalPartLen = strlen($decimal) - 2;
return (number_format($decimal, $decimalPartLen) <= number_format($decimalBreakPart, $decimalPartLen) ? $whole : ceil($value));
}
Proof:
http://sandbox.onlinephpfunctions.com/code/d75858f175dd819de069a8a05611ac9e7053f07a
You can specify "break part" if you want.

Rounding a calculation up using php

How would I round this calculation up automatically??
$calc = (14.3/10)/2.33 Result = 6.137339055794
The value I would like to have is 6.13
Have searched the site but can't find any answers on this
Use PHP round().
$calc = round($calc, 2)
The result of (14.3/10)/2.33 is not 6.137339055794. It's 0.6137339055794.
I'm assuming: $calc = (14.3/10) / 2.33 * 10;.
The function round rounds half up, half down, half even or half odd numbers (floating point numbers), but the result of round($calc, 2, PHP_ROUND_HALF_UP) is not 6.13. It's 6.14.
Assuming you'd like to round down or truncate that number, a solution could be:
$truncated = (int)($calc * 100) / 100;
or
$precision = 2;
$tensPrecision = pow(10, $precision);
$truncated = (int)($calc * $tensPrecision) / $tensPrecision;
.
To round up, you could do:
$truncated = ceil($calc * 100) / 100;
or
$precision = 2;
$tensPrecision = pow(10, $precision);
$truncated = ceil($calc * $tensPrecision) / $tensPrecision;

Rounding down numbers to set points with PHP

I have a basic 5 star rating system based on user submissions. depending on the rating, a particular image is shown.
$user_rating contains the rating number to one decimal place.
There are 'star' images with
0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0
in the file names.
I need whatever number is contained in $user_rating to be rounded down to the nearest value above and stored in a new variable $star_rating. The numbers can never be rounded up. Even if $user_rating is 4.9, $star_rating should be 4.5.
Can someone help me achieve this?
Thanks
EDIT - using this but just returns original value - in this case 3.8
$star_rating = $user_rating;
function roundToHalf($star_rating) {
$temp = $star_rating * 10;
$remainder = $star_rating % 5;
return ($temp - $remainder) / 10;
}
<?php
function roundRating($rating, array $ratings)
{
if (in_array($rating, $ratings))
{
return $rating;
}
foreach($ratings as $key => $value)
{
if ($value > $rating)
{
return $ratings[($key - 1)];
}
}
return FALSE;
}
$ratings = array(0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0);
$rating = 4.3;
if ($rate = roundRating($rating, $ratings))
echo sprintf('%.01f', $rate);
Demo: http://3v4l.org/BRBne
A simple approach:
function roundToHalf($star_rating) {
return floor( $star_rating * 2 ) / 2;
}
This works because you're looking values evenly divisible by .5 . The result is a float. I think you're better off getting back a numerical value, in case you want to use it for mathematical purposes. Let your display code format it as needed.
function roundDownToHalf($number) {
$remainder = ($number * 10) % 10;
$half = $remainder >= 5 ? 0.5 : 0;
$value = floatval(intval($number) + $half);
return number_format($value, 1, '.', '');
}
define("ENDL", "\n");
print roundDownToHalf(4.9) . ENDL;
print roundDownToHalf(4.5) . ENDL;
print roundDownToHalf(3.8) . ENDL;
print roundDownToHalf(2.3) . ENDL;
print roundDownToHalf(1.0) . ENDL;
print roundDownToHalf(0.6) . ENDL;
Output
4.5
4.5
3.5
2.0
1.0
0.5
All in one compact function:
function roundDownToHalf($n) {
return number_format(floatval(intval($n)+((($n*10)%10)>=5?.5:0)),1,'.','');
}
Multiply by 10 to make it into an integer than use the modulus operator '%' to remove the remainder. Then divide by 10 to make it back into a decimal.
function roundToHalf($number) {
$temp = intval($number * 10);
$remainder = $temp % 5;
return ($temp - $remainder) / 10;
}

Converting string to integer from form

Need a little help
I have
$_POST["zapremina"]=2000;
$_POST["starost"]="15%";
$_POST["namena"]="50%";
I want simple function to do this
$foo=(2000 - 15%) - 50%;
How to do that?
PHP is loosely typed, so you don't have to cast types explicity or do unnecessary operations (e.g. str_replace)
You can do the following:
$z = $_POST["zapremina"]; //$_POST["zapremina"]=2000;
$s = $_POST["starost"]; //$_POST["starost"]=15%;
$n = $_POST["namena"]; //$_POST["namena"]="50%;
$result = (($z - ($z *($s / 100))) - ($z * ($n / 100)));
Remember to use parentheses to have a readable code and meaningful var names.
Like this:
$starostPercentage = (substr($POST["starost"], 0, -1) / 100);
$namenaPercentage = (substr($POST["namena"], 0, -1) / 100);
$foo = ($_POST["zapremina"] * (100 - $starostPercentage)) * $namenaPercentage;
This is what this does and why:
Convert the percentages (like 15%) from their text form to their decimal form (substr(15%) = 15, 15 / 100 = 0.15).
Calculate $foo with these decimals. 2000 - 15% is what you would write (as a human), but in PHP you need to write that as 2000 * (100 * 0.15), meaning: 85% of 2000).
I'd go with this:
$zap = intval($_POST['zapremina']);
$sta = intval($_POST['starost']);
$nam = intval($_POST['namena']);
$foo = ($zap * ((100-$sta)/100)) * ((100 - $nam)/100)
add this function and then call it
function calculation($a, $b, $c)
{
$b = substr($b, 0, -1) / 100;
$c = substr($c, 0, -1) / 100;
return (($a * $b) * $c);
}
and now you can call
$foo = calculation($_POST["zapremina"], $_POST["starost"], $_POST["namena"]);
go with function most of times, because it will be helpful for reusability.

Categories