In my database I store the amount of a user in cents.
Now I need to convert user input to integer.
input of user(string) :|output (int):
1.00 100
1 100
1,51 151
I have no idea, how to solve this. Formatting amounts like: 1.00 and 1,00 isn't a big problem, but what's the best way to format the amount like "1" to the right amount of cents?
What I use at the moment (not working with inputs like "1"):
$value = intval(str_replace([',','.'],'', $request->amount));
What about casting as a float and multiplying by 100?
<?php
header("Content-type: text/plain");
$x = '1,51';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1.51';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1,00';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
$x = '1.00';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";
returns:
151
100
151
100
100
str_replace should be used with two arrays or two strings
$value = intval(str_replace([',','.'],['',''], $request->amount));
Related
I'm looking for a formula to round a value to nearest 5 or 9 if the val is less than 5 make 5 if is bigger than 5 make 9.
Example:
$RoundToFive = ceil('232' / 5) * 5;
echo floor($RoundToFive * 2 ) / 2; //Result is 235 Is good
$RoundToNine = ceil('236' / 5) * 5;
echo floor($RoundToNine * 2 ) / 2; //Result is 240 but i need 239
Is there a way to extract always the last 2 digits and convert to 5 or nine ?
Any help is appreciated !
how about:
function funnyRound($number){
$rounded = ceil($number / 5) * 5;
return $rounded%10?$rounded:$rounded-1;
}
This is working
<?php
function roundToDigits($num, $suffix, $type = 'floor') {
$pow = pow(10, floor(log($suffix, 10) + 1));
return $type(($num - $suffix) / $pow) * $pow + $suffix;
};
$RoundToNine = ceil('236' / 5) * 5;
echo roundToDigits($RoundToNine,5);
echo roundToDigits($RoundToNine,9);
You can use any number as $suffix to round to it.
other way, working with strings... :
<?php
function round59($NUMB){
//cast the value to be Int
$NUMB = intval($NUMB);
//Get last number
$last_number = intval(substr($NUMB, -1));
$ROUND_NUMBER = 5;
if($last_number<=5)
$ROUND_NUMBER = 5;
else
$ROUND_NUMBER = 9;
//Remove Last Character
$NUMB = substr($NUMB, 0, -1);
// now concat the results
return intval($NUMB."".$ROUND_NUMBER) ;
}
echo round59(232);
echo round59(236);
?>
I've searched through a number of similar questions, but unfortunately I haven't been able to find an answer to this problem. I hope someone can point me in the right direction.
I need to come up with a PHP function which will produce a random number within a set range and mean. The range, in my case, will always be 1 to 100. The mean could be anything within the range.
For example...
r = f(x)
where...
r = the resulting random number
x = the mean
...running this function in a loop should produce random values where the average of the resulting values should be very close to x. (The more times we loop the closer we get to x)
Running the function in a loop, assuming x = 10, should produce a curve similar to this:
+
+ +
+ +
+ +
+ +
Where the curve starts at 1, peeks at 10, and ends at 100.
Unfortunately, I'm not well versed in statistics. Perhaps someone can help me word this problem correctly to find a solution?
interesting question. I'll sum it up:
We need a funcion f(x)
f returns an integer
if we run f a million times the average of the integer is x(or very close at least)
I am sure there are several approaches, but this uses the binomial distribution: http://en.wikipedia.org/wiki/Binomial_distribution
Here is the code:
function f($x){
$min = 0;
$max = 100;
$curve = 1.1;
$mean = $x;
$precision = 5; //higher is more precise but slower
$dist = array();
$lastval = $precision;
$belowsize = $mean-$min;
$abovesize = $max-$mean;
$belowfactor = pow(pow($curve,50),1/$belowsize);
$left = 0;
for($i = $min; $i< $mean; $i++){
$dist[$i] = round($lastval*$belowfactor);
$lastval = $lastval*$belowfactor;
$left += $dist[$i];
}
$dist[$mean] = round($lastval*$belowfactor);
$abovefactor = pow($left,1/$abovesize);
for($i = $mean+1; $i <= $max; $i++){
$dist[$i] = round($left-$left/$abovefactor);
$left = $left/$abovefactor;
}
$map = array();
foreach ($dist as $int => $quantity) {
for ($x = 0; $x < $quantity; $x++) {
$map[] = $int;
}
}
shuffle($map);
return current($map);
}
You can test it out like this(worked for me):
$results = array();
for($i = 0;$i<100;$i++){
$results[] = f(20);
}
$average = array_sum($results) / count($results);
echo $average;
It gives a distribution curve that looks like this:
I'm not sure if I got what you mean, even if I didn't this is still a pretty neat snippet:
<?php
function array_avg($array) { // Returns the average (mean) of the numbers in an array
return array_sum($array)/count($array);
}
function randomFromMean($x, $min = 1, $max = 100, $leniency = 3) {
/*
$x The number that you want to get close to
$min The minimum number in the range
$max Self-explanatory
$leniency How far off of $x can the result be
*/
$res = [mt_rand($min,$max)];
while (true) {
$res_avg = array_avg($res);
if ($res_avg >= ($x - $leniency) && $res_avg <= ($x + $leniency)) {
return $res;
break;
}
else if ($res_avg > $x && $res_avg < $max) {
array_push($res,mt_rand($min, $x));
}
else if ($res_avg > $min && $res_avg < $x) {
array_push($res, mt_rand($x,$max));
}
}
}
$res = randomFromMean(22); // This function returns an array of random numbers that have a mean close to the first param.
?>
If you then var_dump($res), You get something like this:
array (size=4)
0 => int 18
1 => int 54
2 => int 22
3 => int 4
EDIT: Using a low value for $leniency (like 1 or 2) will result in huge arrays, since testing, I recommend a leniency of around 3.
If I have the following code which grabs an array of values and adds them all together, how can I then round them down to the nearest 10000 using PHP?
Here's the code I currently have
$rows = $db->get("sales");
$sales = 0;
foreach($rows as $row) {
$stock = $sales + $row['sales'];
}
return $sales;
An example result would be
146740
How could I then make that returned as
140000
Although if I had a number greater than 1 million, how could I have that returned as just 1 million?
Divide by 10000, use floor to round down to an integer, then multiply by 10000:
$x = 146740;
$x = 10000 * floor($x/10000);
Or subtract the remainer:
$x = 146740;
$x = $x - ($x % 10000);
To extend this to 1 million, you can do:
if ($x > 1000000) {
$divisor = 1000000;
} elseif ($x > 10000) {
$divisor = 10000;
} else {
$divisor = 1;
}
$x = $x - ($x % divisor);
you could divide the value by 1000. If it is integer 146740/1000 = 146. And after that multiply by 1000 will give 146000
How can I make calculation pieces in PHP?
This is my calculation
605,00 / 5% = 30.25.
How can I calculate this in PHP?
$a = 605.00;
$b = 5 (percentage)
How I have tried, but this did not work
$total = ($a / 0.5);
You could do:
$number = 605;
$percentage = 5;
$total = $number * ($percentage / 100);
Actually if you divide 5 by 100, it will equal 0.05 so try $b = .05;.
In basic math, the first decimal is calculated in 10ths, then 100ths, then 1000ths
Just do $total = ($a / $b);
Tested. Total = 12,100 yet will echo 12100
<?php
$a = 605.00;
$b = 0.05;
$total = ($a / $b);
echo $total; // will echo 12100
?>
I have a number X, consider X = 1000
And I want piecemeal this number at three times, then Y = 3, then X = (X / 3)
This will give me equal, just not always accurate, so I need: a percentage value is set, also consider K = 8, K is the percentage, but what I want to do? I want the first portion has a value over 8% in K, suppose that 8% are: 500 and the other two plots are 250, 250
The algorithm is basically what I need it, add a percentage value for the first installment and the other equals
EDIT
I just realized, this is far simpler than I made it. To find the value of $div in my original answer you can just:
$div = (int)($num / ($parcels + $percent / 100));
Then the $final_parcels will be the same as below. Basically, the line above replaces the while loop entirely. Don't know what I was thinking.
/EDIT
I think this will do what you want... unless I am missing something.
<?php
$num = 1000;
$percent = 8;
$parcels = 3;
$total = PHP_INT_MAX;
$div = (int)($num / $parcels);
while ($total > $num) {
$div -= 1;
$total = (int)($div * ($parcels + $percent / 100));
}
$final_parcels = array();
$final_parcels[] = ($num - (($parcels - 1) * $div));
for ($i = 1; $i < $parcels; $i++) {
$final_parcels[] = $div;
}
print_r($final_parcels);
This output will be
Array
(
[0] => 352
[1] => 324
[2] => 324
)
324 * 1.08 = 350.
352 + 324 * 2 = 1000.
Let $T is your total X, $n is a number of parts and $K is percentage mentioned above. Than
$x1 = $T / $n + $T * $K / 100;
$x2 = $x3 = .. = $xn = ($T - $x1) / ($n - 1);
Applied to your example:
$x1 = 1000 / 3 + 1000 * 0.03 = 363.3333333333333333333333333333
// you could round it if you want
// lets round it to ten, as you mentioned
$x1 = round($x1, -1) = 360
$x2 = $x3 = (1000 - 360) / 2 = 320
Extra for the first piece W = X*K/100
Remaining Z = X-W
Each non-first piece = Z/Y = (X-W)/Y = (100-K)*X/(100*Y)
The first piece = W + (100-K)*X/(100*Y) = X*K/100 + (100-K)*X/(100*Y)