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;
Related
I would like to format (round) float (double) numbers to lets say 2 significant digits for example like this:
1 => 1
11 => 11
111 => 110
119 => 120
0.11 => 0.11
0.00011 => 0.00011
0.000111 => 0.00011
So the arbitrary precision remains same
I expect there is some nice function for it already built in, but could not find any so far
I was pointed to How to round down to the nearest significant figure in php, which is close but doesn't work for N significant digits and I'm not sure what it does with 0.000XXX numbers
To get a number rounded to n significant figures you need to find the size of the number in powers of ten, and subtract that from n.
This works fine for simple rounding:
function sigFig($value, $digits)
{
if ($value == 0) {
$decimalPlaces = $digits - 1;
} elseif ($value < 0) {
$decimalPlaces = $digits - floor(log10($value * -1)) - 1;
} else {
$decimalPlaces = $digits - floor(log10($value)) - 1;
}
$answer = round($value, $decimalPlaces);
return $answer;
}
This will give the following:
0.0001234567 returns 0.0001235
123456.7 returns 123500
However a value such as 10 to four significant figures should strictly be represented as 10.00 to signify the precision to which the value is known.
If this is the desired output you can use the following:
function sigFig($value, $digits)
{
if ($value == 0) {
$decimalPlaces = $digits - 1;
} elseif ($value < 0) {
$decimalPlaces = $digits - floor(log10($value * -1)) - 1;
} else {
$decimalPlaces = $digits - floor(log10($value)) - 1;
}
$answer = ($decimalPlaces > 0) ?
number_format($value, $decimalPlaces) : round($value, $decimalPlaces);
return $answer;
}
Now 1 is displayed as 1.000
With little modification to possible duplicate, answer by Todd Chaffee:
public static function roundRate($rate, $digits)
{
$mod = pow(10, intval(round(log10($rate))));
$mod = $mod / pow(10, $digits);
$answer = ((int)($rate / $mod)) * $mod;
return $answer;
}
To make sigFig(0.9995, 3) output 1.00, use
if(floor(log10($value)) !== floor(log10(round($value, $decimalPlaces)))) {$decimalPlaces--;}
Said line of code should be placed before declaring $answer.
If input $value is negative, set a flag and remove the sign at the beginning of the function, like this:
if($value < 0){$flag = 1;}
$value = ltrim($value, "-");
Then right before returning $answer, detect if the flag is set and if so restore the negative sign, like this:
if(isset($flag)){$answer = "-".$answer;}
Finally, for result values with ambiguous number of significant digits (e.g., 1000, 12000,...), express the result in scientific notation to the desired number of significant digits using sprintf or printf.
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 have this if statement:
if($_GET["angle_1"] > 39) {
$markers["###ANGLE###"] = "45";
} elseif($_GET["angle_1"] > 29 && $_GET["angle_1"] < 40) {
$markers["###ANGLE###"] = "35";
} elseif($_GET["angle_1"] < 30) {
$markers["###ANGLE###"] = "25";
} else {
$markers["###ANGLE###"] = "45";
}
Is there a better / simpler way to do this check, f.x. with round that will round the integer to the nearest 5, i.e. 28 -> 25 or 34 -> 35 etc. and in that, if the integer is less than 25, it will always be 25 and if the integer is higher than 45, it will always be 45 and again if the integer is between 30 and 40 it will always be 35.
That returned value will be used to display an image.
EDIT:
I have 3 images: image_25, image_35 and image_45, therefore the need to round.
Let say $x has the number:
$x = 39;
If you want the closest multiple of 5 (39 --> 40):
$x = round($x / 5) * 5;
If you want to round up (36 --> 40):
$x = ceil($x / 5) * 5;
If you want to round down (39 --> 35):
$x = floor($x / 5) * 5;
After defining $x, you can use the following to make sure its in the 25-45 range:
$x = ($x > 45) ? 45 : ($x < 25) ? 25 : $x;
Give this a try:
$var = 5 * round($n / 5);
Taken from here
I am using the following PHP code to calculate a CRN for BPay:
<?php
function LuhnCalc($number) {
$chars = array_reverse(str_split($number, 1));
$odd = array_intersect_key($chars, array_fill_keys(range(1, count($chars), 2), null));
$even = array_intersect_key($chars, array_fill_keys(range(0, count($chars), 2), null));
$even = array_map(function($n) { return ($n >= 5)?2 * $n - 9:2 * $n; }, $even);
$total = array_sum($odd) + array_sum($even);
return ((floor($total / 10) + 1) * 10 - $total) % 10;
}
print LuhnCalc($_GET['num']);
?>
However it seems that BPAY is version 5 of MOD 10, for which I can't find any documentation. It seems to not be the same as MOD10.
The following numbers where tested:
2005,1597,3651,0584,9675
bPAY
2005 = 20052
1597 = 15976
3651 = 36514
0584 = 05840
9675 = 96752
MY CODE
2005 = 20057
1597 = 15974
3651 = 36517
0584 = 05843
9675 = 96752
As you can see, none of them match the BPAY numbers.
This PHP function will generate BPay reference numbers based on the mod10 version 5 algorithm.
Who knows why BPay can't add this to their website. I only found an explanation by googling finding the algorithm being called "MOD10V05" instead of "Mod 10 version 5".
function generateBpayRef($number) {
$number = preg_replace("/\D/", "", $number);
// The seed number needs to be numeric
if(!is_numeric($number)) return false;
// Must be a positive number
if($number <= 0) return false;
// Get the length of the seed number
$length = strlen($number);
$total = 0;
// For each character in seed number, sum the character multiplied by its one based array position (instead of normal PHP zero based numbering)
for($i = 0; $i < $length; $i++) $total += $number{$i} * ($i + 1);
// The check digit is the result of the sum total from above mod 10
$checkdigit = fmod($total, 10);
// Return the original seed plus the check digit
return $number . $checkdigit;
}
Here's a way of implementing the "MOD10V5" algorithm (or "mod 10 version 5") using a t-sql user defined function in SQL server. It accepts a Customer ID up to 9 characters long, and return an 11 character CRN (Customer Reference Number).
I also prepended a version number onto the start of my CustomerID, you could do this too if you think you might end up changing it in the future.
CREATE Function [dbo].[CalculateBPayCRN]
(
#CustomerID nvarchar(9)
)
RETURNS varchar(11)
AS
BEGIN
DECLARE #NewCRN nvarchar(11)
DECLARE #Multiplier TINYINT
DECLARE #Sum int
DECLARE #SubTotal int
DECLARE #CheckDigit int
DECLARE #ReturnVal BIGINT
SELECT #Multiplier = 1
SELECT #SubTotal = 0
-- If it's less than 9 characters, pad it with 0's, then prepend a '1'
SELECT #NewCRN = '1' + right('000000000'+ rtrim(#CustomerID), 9)
-- loop through each digit in the #NewCRN, multiple it by the correct weighting and subtotal it:
WHILE #Multiplier <= LEN(#NewCRN)
BEGIN
SET #Sum = CAST(SUBSTRING(#NewCRN,#Multiplier,1) AS TINYINT) * #Multiplier
SET #SubTotal = #SubTotal + #Sum
SET #Multiplier = #Multiplier + 1
END
-- mod 10 the subtotal and the result is our check digit
SET #CheckDigit = #SubTotal % 10
SELECT #ReturnVal = #NewCRN + cast(#CheckDigit as varchar)
RETURN #ReturnVal
END
GO
Modula 10 V1 in PHP. Tested against my Windows dataflex routine and it is the same.
function generateBpayRef($number) {
//Mod 10 v1
$number = preg_replace("/\D/", "", $number);
// The seed number needs to be numeric
if(!is_numeric($number)) return false;
// Must be a positive number
if($number <= 0) return false;
$stringMemberNo = "$number";
$stringMemberNo = str_pad($stringMemberNo, 6, "0", STR_PAD_LEFT);
//echo " Padded Number is $stringMemberNo ";
$crn = $stringMemberNo;
for($i=0;$i<7;$i++){
$crnval = substr($crn,(5-$i),1);
$iPartVal = $iWeight * $crnval;
if($iPartVal>9){
//echo " Greater than 9: $iPartVal ";
$firstChar = substr($iPartVal,0,1);
$secondChar = substr($iPartVal,1,1);
$iPartVal=$firstChar+$secondChar;
//$iPartVal -= 9;
}
$iSum+=$iPartVal;
$iWeight++;
if ($iWeight>2){$iWeight=1;}
//echo " CRN: $crnval ] Weight: $iWeight ] Part: $iPartVal ] SUM: $iSum ";
}
$iSum %= 10;
if($iSum==0){
//echo " zero check is $iSum ";
//return $iSum;
}
else{
//return 10-$iSum;
$iSum=(10-$iSum);
}
//echo " Check is a $iSum ";
$BpayMemberNo = $stringMemberNo . $iSum ;
echo " New: $BpayMemberNo ";
return ($BpayMemberNo);
}
Here is a ruby class I whipped up quickly for Mod 10 v5
module Bpay
class CRN
attr_accessor :number, :crn
class << self
def calculate_for(number)
new(number).crn
end
end
def initialize(number)
#number = number
calculate
end
def calculate
raise ArgumentError, "The number '#{number}' is not valid" unless valid?
digits = number.to_s.scan(/\d/).map { |x| x.to_i }
raise ArgumentError, "The number '#{number}' must be at least 2 digits in length" if digits.size < 2
check_digit = digits.each_with_index.map { |d, i| d * (i + 1) }.inject(:+) % 10
#crn = "#{number}#{check_digit}"
end
def valid?
return false unless !!Integer(number.to_s) rescue false
return false if number.to_i <= 0
true
end
end
end
This is in C#, but this is what I have so far for BPay check digit generation:
private void btnBPayGenerate_Click(object sender, EventArgs e)
{
var originalChars = txtBPayNumber.Text.ToCharArray();
List<int> oddDigits = new List<int>();
List<int> evenDigits = new List<int>();
int oddTotal = 0, evenTotal = 0, total = 0, checkDigit ;
const int oddMultiplier = 3;
const int modulus = 10;
bool isOdd = true;
for (int x = 0; x < originalChars.Length; x++)
{
if(isOdd)
oddDigits.Add(Int32.Parse(originalChars[x].ToString()));
else
evenDigits.Add(Int32.Parse(originalChars[x].ToString()));
isOdd = !isOdd;
}
foreach (var digit in oddDigits)
oddTotal += digit;
foreach (var digit in evenDigits)
evenTotal += digit;
oddTotal = oddTotal * oddMultiplier;
total = oddTotal + evenTotal;
checkDigit = (modulus - (total % modulus));
lblBPayResult.Text = txtBPayNumber.Text + checkDigit.ToString();
}
I haven't completed testing this yet, I will post back once BPAY get back to me.
EDIT: try this: https://gist.github.com/1287893
I had to work out a version for javascript, this is what I came up with. It correctly generates the expected numbers in the original question.
var startingNumber = 2005;
var reference = startingNumber.toString();
var subTotal = 0;
for (var x = 0; x < reference.length; x++) {
subTotal += (x + 1) * reference.charAt(x);
}
var digit = subTotal % 10;
var bpayReference = reference + digit.toString();
Here is a function I created using vb.net to calculate a mod 10 version 5 check digit
Private Function CalcCheckDigit(ByRef psBaseNumber As String) As String
Dim lCheckDigit, iLoop As Integer
Dim dCalcNumber As Double
lCheckDigit = 0
dCalcNumber = 0
For iLoop = 0 To (psBaseNumber.Length - 1)
lCheckDigit = lCheckDigit + (psBaseNumber.Substring(iLoop, 1) * (iLoop + 1))
Next iLoop
lCheckDigit = lCheckDigit Mod 10
CalcCheckDigit = psBaseNumber & CStr(lCheckDigit)
End Function
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)