Convert .5 into 1/2 - php

I want to convert any number which ends in .5 so that it displays as the number followed by ½, but I don't want 0.5 to display as 0½ so I did it like this:
$used = str_replace("0.5", "½", $used);
$used = str_replace(".5", "½", $used);
However I've now realised that this also converts 20.5 into 2½ instead of 20½.
I'm sure there's a better way of doing it but I don't know how.
Examples:
5 returns "5"
5.5 returns "5½"
0.5 returns "½"
10.5 returns "10½"
I don't believe this is a duplicate of an existing question because that code is to replace or return "1/2" rather than "½"

Based on the examples above and lacking any further requirements, you could write:
<?php
$n = "13.5";
/* ... */
$r = $n;
$r = preg_replace ('/^0\.5$/', '½', $r);
$r = preg_replace ('/\.5$/', '½', $r);
echo "$r\n";
You can combine the above into a single replacement:
$r = preg_replace ('/(^0|)\.5$/', '½', $n);

PHP code demo(In HTML it will work fine)
<?php
$number="10.5000";
if(preg_match("/^[1-9][0-9]*\.5[0]{0,}$/", $number))
{
echo $used = preg_replace("/\.5[0]{0,}$/", "½", $number);
}
elseif(preg_match("/^[0]*\.5[0]{0,}$/", $number))
{
echo $used = str_replace("$number", "½", $number);
}
else
{
echo $number;
}
Output:
10½

Related

Is there a specific function that allows me to round up to a specific decimal number in PHP

I have a number that needs to be rounded up to a specific decimal, is there any function in PHP to do that?
I need every number (which reflects an amount of money) to have a specific decimal number.
For example:
The decimal needs to be 25, so if I got $ 25.50 I need it to be $ 26.25, and if I got $ 25.10 it needs to be $ 25.25.
I've checked PHP round(), and specifically ceil(), and I've come across this answer in Python, but I'm not sure it applies to my case, because what I need is different.
Any ideas? Even pseudo code as a tip on where to start will help me. Thanks!
I think you need a custom function, something like this:
function my_round($number, $decimal = 0.25) {
$result = floor($number) + $decimal;
if ($result < $number) $result = ceil($number) + $decimal;
return $result;
}
print my_round(25.50);
I modified this answer for your case:
<?php
function roundUp($number){
$int = floor($number);
$float = $number-$int;
if ($float*10 < 2.5)
$result = $int;
else
$result = ceil($number);
$result+= 0.25;
echo $number." becomes ".$result."\n";
}
roundUp(25.50);
roundUp(25.10);
Look for demo here
Following axiac's advice mentioned in the comments and following this thread, the best way to deal with floating point numbers in the context of currencies, is to treat the dollars and cents' values as 2 separate entities.
One way I can think of it to split the numbers before and after the decimal into 2 separate variables and process accordingly.
<?php
function customRound($amount){
$amount = strval($amount);
if(preg_match('/(\d+)\.?(\d{1,2})?/', $amount, $matches) !== 1){
throw new \Exception("Invalid amount.");
}
$dollars = intval($matches[1]);
$cents = intval($matches[2] ?? 0);
if($cents < 10) $cents *= 10;
if($cents <= 25) return $dollars . ".25";
return ($dollars + 1) . ".25";
}
$tests = [25.51,25.49,26.25,25.10,25.49];
foreach ($tests as $test){
echo $test," => ",customRound($test),PHP_EOL;
}
Here's another approach:
<?php
function roundUp($number, $decimal=0.25){
$dollars = floor($number);
$cents = $number - $dollars;
if($cents > $decimal) {
++$dollars;
}
return $dollars + $decimal;
}
echo roundUp(25.50).PHP_EOL;
echo roundUp(25.10);

Replacing random numbers in a php string serial numbers(123...)

In PHP, how to convert a string containing mixture of random letters and numbers to a string containing serial numbers along with random numbers without changing their position in a string? For example,
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
Now, I want to convert this string into
$str_b = "1)Apple 2)Ball 3)Cat 4)Dog 5)Egg";
I want the numbers 1,5,3,8,4 to be 1,2,3,4,5.
This should work for you:
Just use preg_replace_callback() and replace each digit (\d+ => 0-9 as many times as possible) with an incrementing number, .e.g
<?php
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
$start = 1;
echo $newStr = preg_replace_callback("/\d+/", function($m)use(&$start){
return $start++;
}, $str_a);
?>
output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg
Created Simple looping program:
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
function change($str_a) {
$counter = 1;
for($i=0; $i<strlen($str_a); $i++) {
if(is_numeric($str_a[$i])) {
$str_a[$i] = $counter++;
}
}
return $str_a;
}
print(change($str_a))
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg
You can use preg_split and then concatenate it incrementing by 1. This will work also for numbers consisting of multiple digits:
$str_a = "51)Apple 675)Ball 334)Cat 84)Dog 904)Egg";
$a = preg_split('/\b\d+/', $str_a);
$str_b = '';
for($i=0,$c = count($a);$i<$c;$i++){
if($i){
$str_b .= $i.$a[$i];
}
}
echo $str_b;
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg

Numbers to letters with logical sequence

I have this array which links numbers to letters at the moment like this:
1-26 = A-Z
But there is more, 27=AA and 28=AB etc...
so basically when I do this:
var_dump($array[2]); //shows B
var_dump($array[29]); //shows AC
Now this array I made myself but it's becoming way too long. Is there a way to actually get this going on till lets say 32? I know there is chr but I dont think I can use this.
Is there an easier way to actually get this without using this way too long of an array?
It's slower calculating it this way, but you can take advantage of the fact that PHP lets you increment letters in the same way as numbers, Perl style:
function excelColumnRange($number) {
$character = 'A';
while ($number > 1) {
++$character;
--$number;
}
return $character;
}
var_dump(excelColumnRange(2));
var_dump(excelColumnRange(29));
here is the code which you are looking for :
<?php
$start = "A";
$max = 50;
$result = array();
for($i=1; $i<=$max; $i++) {
$result[$i] = $start++;
}
print_r($result);
?>
Ref: http://www.xpertdeveloper.com/2011/01/php-strings-unusual-behaviour/
This should work for you:
Even without any loops. First I calculate how many times the alphabet (26) goes into the number. With this I define how many times it has to str_repleat() A. Then I simply subtract this number and calculate the number in the alphabet with the number which is left.
<?php
function numberToLetter($number) {
$fullSets = (($num = floor(($number-1) / 26)) < 0 ? 0 : $num);
return str_repeat("A", $fullSets) . (($v = ($number-$fullSets*26)) > 0 ? chr($v+64) : "");
}
echo numberToLetter(53);
?>
output:
AAA

PHP Image counter number formatting

I'm building a counter that counts and displays on a web page the number of images in a certain directory.
The code I'm currently using is this:
<?
$d = opendir("images/myimagefolder");
$count = 0;
$min_digits = 7;
while(($f = readdir($d)) !== false)
if(ereg('.jpg$', $f))
++$count;
closedir($d);
if ($min_digits)
{
$count = sprintf('%0'.$min_digits.'f', $count);
}
$number = $count;
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split($formattedNumber, 3);
$formattedNumber = implode(",", $formattedNumber);
print "$formattedNumber";
?>
This works well and outputs a number like the following: 000,000,5
What I am wanting is to have the separating commas occur every 3 digits from the right not the left, so it would appear as 0,000,005
How would this this be done?
I have tried a number of modifications to my sprintf and str_split code but nothing has worked so far. Any help would be greatly appreciated!
<?php
//image count
$images=count(glob("images/myimagefolder/*.jpg"));
//padding
$images=sprintf("%07s",$images);
//commas
$images=strrev(implode(",",str_split(strrev($images),3)));
//outputs 0,000,005
echo $images;
?>
Had a bit of fun coming up with the shortest possible way to accomplish your solution. :)
$formattedNumber = sprintf("%07d", $number);
$formattedNumber = str_split(strrev($formattedNumber), 3);
for (i=0;i<count($formattedNumber); i++)
$formattedNumber[i] = strrev($formattedNumber[i]);
$formattedNumber = implode(",", array_reverse($formattedNumber));
Drop the last four lines. All you need is 'print number_format ($count);'
http://php.net/manual/en/function.number-format.php
Edit, the above won't work with the leading 0's
I found this in the comments on the php site. A little regex magic should do it in one line.
print preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",",",$count);
Here's my take with arrays:
$num = sprintf("%07d", 5);
$digits = str_split($num, 1);
$digits = array_reverse($digits);
$chunks = array_map('array_reverse', array_reverse(array_chunk($digits, 3)));
$concat_chunks = array();
foreach ($chunks as $chunk) {
$concat_chunks[] = join('', $chunk);
}
$output = join(',', $concat_chunks);
print $output;

Swap every pair of characters in string

I'd like to get all the permutations of swapped characters pairs of a string. For example:
Base string: abcd
Combinations:
bacd
acbd
abdc
etc.
Edit
I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.
What's the best way to do this?
Edit
Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?
Speed test
I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)
Edit: Markdown hates me today...
$input = "abcd";
$len = strlen($input);
$output = array();
for ($i = 0; $i < $len - 1; ++$i) {
$output[] = substr($input, 0, $i)
. substr($input, $i + 1, 1)
. substr($input, $i, 1)
. substr($input, $i + 2);
}
print_r($output);
nickf made beautiful solution thank you , i came up with less beautiful:
$arr=array(0=>'a',1=>'b',2=>'c',3=>'d');
for($i=0;$i<count($arr)-1;$i++){
$swapped="";
//Make normal before swapped
for($z=0;$z<$i;$z++){
$swapped.=$arr[$z];
}
//Create swapped
$i1=$i+1;
$swapped.=$arr[$i1].$arr[$i];
//Make normal after swapped.
for($y=$z+2;$y<count($arr);$y++){
$swapped.=$arr[$y];
}
$arrayswapped[$i]=$swapped;
}
var_dump($arrayswapped);
A fast search in google gave me that:
http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/
How about just using the following:
function swap($s, $i)
{
$t = $s[$i];
$s[$i] = $s[$i+1];
$s[$i+1] = $t;
return $s;
}
$s = "abcd";
$l = strlen($s);
for ($i=0; $i<$l-1; ++$i)
{
print swap($s,$i)."\n";
}
Here is a slightly faster solution as its not overusing substr().
function swapcharpairs($input = "abcd") {
$pre = "";
$a="";
$b = $input[0];
$post = substr($input, 1);
while($post!='') {
$pre.=$a;
$a=$b;
$b=$post[0];
$post=substr($post,1);
$swaps[] = $pre.$b.$a.$post;
};
return $swaps;
}
print_R(swapcharpairs());

Categories