I assumed there'd be an easy way in PHP to convert a string like 18 5/16 into the float 18.3125. I can't find a straightforward function to do it. Is there one, or do I need to write my own?
I don't think such a function exists -- at least not bundled with PHP.
Writing a function that does this operation, if your string always have the same format, should not be too hard ; for example, I'd say that something like this should do the trick :
$str = '18 5/16';
var_dump(calc($str));
function calc($str) {
$int = 0;
$float = 0;
$parts = explode(' ', $str);
if (count($parts) >= 1) {
$int = $parts[0];
}
if (count($parts) >= 2) {
$float_str = $parts[1];
list($top, $bottom) = explode('/', $float_str);
$float = $top / $bottom;
}
return $int + $float;
}
Which will get you the following output :
float 18.3125
And you might get something shorter with a few regex ; something like this should do the trick, I suppose :
function calc($str) {
if (preg_match('#(\d+)\s+(\d+)/(\d+)#', $str, $m)) {
return $m[1] + $m[2] / $m[3];
}
return 0;
}
Else, not bundled in PHP, but already existing, maybe this class could help : Eval Math.
Disclaimer : I have not tested it -- so not quite sure it'll work in your specific situation.
To expand on Pascal's example, here is a more robust solution that can handle fractions greater than 1 and less than 1.
function parseFraction(string $fraction): float
{
if(preg_match('#(\d+)\s+(\d+)/(\d+)#', $fraction, $m)) {
return ($m[1] + $m[2] / $m[3]);
} else if( preg_match('#(\d+)/(\d+)#', $fraction, $m) ) {
return ($m[1] / $m[2]);
}
return (float)0;
}
Here is some basic test coverage, useful to integrate this code with phpunit
class FractionParserTest extends TestCase
{
/**
* < 1
* #return void
*/
public function testSimple(): void
{
$qty = '3/4';
$res = parseFraction($qty);
$this->assertEquals(0.75, $res);
}
/**
* > 1
* #return void
*/
public function testComplex(): void
{
$qty = '18 5/16';
$res = parseFraction($qty);
$this->assertEquals(18.3125, $res);
}
}
Related
So I have this class, which appreciates numbers. For example, AbbreviateNum::convert(1178); will round up and turn it into 1.18K.
This works as it should, nicely. However, I can't seem to figure out how to output negative numbers. If I run AbbreviateNum::convert(-1178);, it will output the same response 1.18K. Without the negative indicator.
Any tips on how I fix this?
<?php
namespace App\Helpers;
class AbbreviateNum
{
/**
* Abbreviate long numbers
*
* #return Response
*/
public static function convert($num)
{
$num = preg_replace('/[^0-9]/', '', $num);
$sizes = array("", "K", "M");
if ($num == 0) return(0);
else return (round($num/pow(1000, ($i = floor(log($num, 1000)))), 2) . $sizes[$i]);
}
}
Here is the modified function that provides a little bit more robustness for the strings it will accept.
public static function convert($num)
{
$num = intval(preg_replace('/[^\-\.0-9]/', '', $num));
$sizes = array("", "K", "M");
if ($num == 0) return(0);
else return (round($num/pow(1000, ($i = floor(log(abs($num), 1000)))), 2) . $sizes[abs($i)]);
}
Simply change the name of the convert Method's argument (num) & do a simple strstr() Check for "-". If found, prefix you result with "-" like this:
<?php
namespace App\Helpers;
class AbbreviateNum
{
/**
* Abbreviate long numbers
*
* #return Response
*/
public static function convert($givenNumber){
$num = preg_replace('/[^0-9]/', '', $givenNumber);
$sizes = array("", "K", "M");
if ($num == 0) {
return(0);
}else {
$number = (round($num/pow(1000, ($i = floor(log($num, 1000)))), 2) . $sizes[$i]);
if(strstr($givenNumber, "-")){
$number = "-" . $number;
}
return $number;
}
}
}
var_dump(AbbreviateNum::convert(-1785));
// PRODUCES: string '-1.79K' (length=6)
var_dump(AbbreviateNum::convert(1785));
// PRODUCES: string '1.79K' (length=5)
Confirm it HERE.
Hope this helps a bit...
Cheers & Good Luck ;-)
For such conversion, I'd use sprintf function:
public static function convert($num) {
$sizes = array("", "K", "M", "G", "T");
$i = 0;
$res = $num;
while (abs($num) > 1000) {$num /= 1000; $i++; $res = sprintf("%.2f$sizes[$i]", $num);}
return $res;
}
I have the following calculation:
$this->count = float(44.28)
$multiple = float(0.36)
$calc = $this->count / $multiple;
$calc = 44.28 / 0.36 = 123
Now I want to check if my variable $calc is integer (has decimals) or not.
I tried doing if(is_int()) {} but that doesn't work because $calc = (float)123.
Also tried this-
if($calc == round($calc))
{
die('is integer');
}
else
{
die('is float);
}
but that also doesn't work because it returns in every case 'is float'. In the case above that should'n be true because 123 is the same as 123 after rounding.
Try-
if ((string)(int) $calc === (string)$calc) {
//it is an integer
}else{
//it is a float
}
Demo
As CodeBird pointed out in a comment to the question, floating points can exhibit unexpected behaviour due to precision "errors".
e.g.
<?php
$x = 1.4-0.5;
$z = 0.9;
echo $x, ' ', $z, ' ', $x==$z ? 'yes':'no';
prints on my machine (win8, x64 but 32bit build of php)
0.9 0.9 no
took a while to find a (hopefully correct) example that is a) relevant to this question and b) obvious (I think x / y * y is obvious enough).
again this was tested on a 32bit build on a 64bit windows 8
<?php
$y = 0.01; // some mambojambo here...
for($i=1; $i<31; $i++) { // ... because ...
$y += 0.01; // ... just writing ...
} // ... $y = 0.31000 didn't work
$x = 5.0 / $y;
$x *= $y;
echo 'x=', $x, "\r\n";
var_dump((int)$x==$x);
and the output is
x=5
bool(false)
Depending on what you're trying to achieve it might be necessary to check if the value is within a certain range of an integer (or it might be just a marginalia on the other side of the spectrum ;-) ), e.g.
function is_intval($x, $epsilon = 0.00001) {
$x = abs($x - round($x));
return $x < $epsilon;
};
and you might also take a look at some arbitrary precision library, e.g. the bcmath extension where you can set "the scale of precision".
You can do it using ((int) $var == $var)
$var = 9;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print true;
$var = 9.6;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print false;
Basically you check if the int value of $var equal to $var
round() will return a float. This is because you can set the number of decimals.
You could use a regex:
if(preg_match('~^[0-9]+$~', $calc))
PHP will convert $calc automatically into a string when passing it to preg_match().
You can use number_format() to convert number into correct format and then work like this
$count = (float)(44.28);
$multiple = (float)(0.36);
$calc = $count / $multiple;
//$calc = 44.28 / 0.36 = 123
$calc = number_format($calc, 2, '.', '');
if(($calc) == round($calc))
die("is integer");
else
die("is not integer");
Demo
Ok I guess I'am pretty late to the party but this is a alternative using fmod() which is a modulo operation. I simply store the fraction after the calculation of 2 variables and check if they are > 0 which would imply it is a float.
<?php
class booHoo{
public function __construct($numberUno, $numberDos) {
$this->numberUno= $numberUno;
$this->numberDos= $numberDos;
}
public function compare() {
$fraction = fmod($this->numberUno, $this->numberDos);
if($fraction > 0) {
echo 'is floating point';
} else {
echo 'is Integer';
}
}
}
$check= new booHoo(5, 0.26);
$check->compare();
Eval here
Edit: Reminder Fmod will use a division to compare numbers the whole documentation can be found here
if (empty($calc - (int)$calc))
{
return true; // is int
}else{
return false; // is no int
}
Try this:
//$calc = 123;
$calc = 123.110;
if(ceil($calc) == $calc)
{
die("is integer");
}
else
{
die("is float");
}
you may use the is_int() function at the place of round() function.
if(is_int($calc)) {
die('is integer');
} else {
die('is float);
}
I think it would help you
A more unorthodox way of checking if a float is also an integer:
// ctype returns bool from a string and that is why use strval
$result = ctype_digit(strval($float));
The string of the hexadecimal number is like: 0X1.05P+10
The real value of this hexadecimal number is:1044.0
I can convert it using C language with method strtod.
But I can't find the way to convert it in PHP. Can somebody show me how to do it?
value string list:
1. "0X1.FAP+9"
2. "0X1.C4P+9"
3. "0X1.F3P+9"
4. "0X1.05P+10"
I think you'll have to make a custom function for this. So because I'm feeling nice today I custom-made one for you:
function strtod($hex) {
preg_match('#([\da-f]+)\.?([\da-f]*)p#i', $hex, $parts);
$i = 0;
$fractional_part = array_reduce(str_split($parts[2]), function($sum, $part) use (&$i) {
$sum += hexdec($part) * pow(16, --$i);
return $sum;
});
$decimal = (hexdec($parts[1]) + $fractional_part) * pow(2, array_pop(explode('+', $hex)));
return $decimal;
}
foreach(array('0X1.FAP+9', '0X1.C4P+9', '0X1.F3P+9', '0X1.05P+10', '0X1P+0') as $hex) {
var_dump(strtod($hex));
};
For versions below PHP 5.3:
function strtod($hex) {
preg_match('#([\da-f]+)\.?([\da-f]*)p#i', $hex, $parts);
$fractional_part = 0;
foreach(str_split($parts[2]) as $index => $part) {
$fractional_part += hexdec($part) * pow(16, ($index + 1) * -1);
}
$decimal = (hexdec($parts[1]) + $fractional_part) * pow(2, array_pop(explode('+', $hex)));
return $decimal;
}
foreach(array('0X1.FAP+9', '0X1.C4P+9', '0X1.F3P+9', '0X1.05P+10', '0X1P+0') as $hex) {
var_dump(strtod($hex));
};
hexdec(0X1.05P+10)
OK so that looks wrong to me as that doesn't look like a proper hex number but its the hexdec() function you want in php http://php.net/manual/en/function.hexdec.php
echo hexdec("0X1FAP")+9
echo hexdec("0X1C4P")+9
echo hexdec("0X1F3P")+9
echo hexdec("0X105P")+10
decimal = hex
(1044.0)10 = (414)16
The function levenshtein in PHP works on strings with maximum length 255. What are good alternatives to compute a similarity score of sentences in PHP.
Basically I have a database of sentences, and I want to find approximate duplicates.
similar_text function is not giving me expected results. What is the easiest way for me to detect similar sentences like below:
$ss="Jack is a very nice boy, isn't he?";
$pp="jack is a very nice boy is he";
$ss=strtolower($ss); // convert to lower case as we dont care about case
$pp=strtolower($pp);
$score=similar_text($ss, $pp);
echo "$score %\n"; // Outputs just 29 %
$score=levenshtein ( $ss, $pp );
echo "$score\n"; // Outputs '5', which indicates they are very similar. But, it does not work for more than 255 chars :(
The levenshtein algorithm has a time complexity of O(n*m), where n and m are the lengths of the two input strings. This is pretty expensive and computing such a distance for long strings will take a long time.
For whole sentences, you might want to use a diff algorithm instead, see for example: Highlight the difference between two strings in PHP
Having said this, PHP also provides the similar_text function which has an even worse complexity (O(max(n,m)**3)) but seems to work on longer strings.
I've found the Smith Waterman Gotoh to be the best algorithm for comparing sentences. More info in this answer. Here is the PHP code example:
class SmithWatermanGotoh
{
private $gapValue;
private $substitution;
/**
* Constructs a new Smith Waterman metric.
*
* #param gapValue
* a non-positive gap penalty
* #param substitution
* a substitution function
*/
public function __construct($gapValue=-0.5,
$substitution=null)
{
if($gapValue > 0.0) throw new Exception("gapValue must be <= 0");
//if(empty($substitution)) throw new Exception("substitution is required");
if (empty($substitution)) $this->substitution = new SmithWatermanMatchMismatch(1.0, -2.0);
else $this->substitution = $substitution;
$this->gapValue = $gapValue;
}
public function compare($a, $b)
{
if (empty($a) && empty($b)) {
return 1.0;
}
if (empty($a) || empty($b)) {
return 0.0;
}
$maxDistance = min(mb_strlen($a), mb_strlen($b))
* max($this->substitution->max(), $this->gapValue);
return $this->smithWatermanGotoh($a, $b) / $maxDistance;
}
private function smithWatermanGotoh($s, $t)
{
$v0 = [];
$v1 = [];
$t_len = mb_strlen($t);
$max = $v0[0] = max(0, $this->gapValue, $this->substitution->compare($s, 0, $t, 0));
for ($j = 1; $j < $t_len; $j++) {
$v0[$j] = max(0, $v0[$j - 1] + $this->gapValue,
$this->substitution->compare($s, 0, $t, $j));
$max = max($max, $v0[$j]);
}
// Find max
for ($i = 1; $i < mb_strlen($s); $i++) {
$v1[0] = max(0, $v0[0] + $this->gapValue, $this->substitution->compare($s, $i, $t, 0));
$max = max($max, $v1[0]);
for ($j = 1; $j < $t_len; $j++) {
$v1[$j] = max(0, $v0[$j] + $this->gapValue, $v1[$j - 1] + $this->gapValue,
$v0[$j - 1] + $this->substitution->compare($s, $i, $t, $j));
$max = max($max, $v1[$j]);
}
for ($j = 0; $j < $t_len; $j++) {
$v0[$j] = $v1[$j];
}
}
return $max;
}
}
class SmithWatermanMatchMismatch
{
private $matchValue;
private $mismatchValue;
/**
* Constructs a new match-mismatch substitution function. When two
* characters are equal a score of <code>matchValue</code> is assigned. In
* case of a mismatch a score of <code>mismatchValue</code>. The
* <code>matchValue</code> must be strictly greater then
* <code>mismatchValue</code>
*
* #param matchValue
* value when characters are equal
* #param mismatchValue
* value when characters are not equal
*/
public function __construct($matchValue, $mismatchValue) {
if($matchValue <= $mismatchValue) throw new Exception("matchValue must be > matchValue");
$this->matchValue = $matchValue;
$this->mismatchValue = $mismatchValue;
}
public function compare($a, $aIndex, $b, $bIndex) {
return ($a[$aIndex] === $b[$bIndex] ? $this->matchValue
: $this->mismatchValue);
}
public function max() {
return $this->matchValue;
}
public function min() {
return $this->mismatchValue;
}
}
$str1 = "Jack is a very nice boy, isn't he?";
$str2 = "jack is a very nice boy is he";
$o = new SmithWatermanGotoh();
echo $o->compare($str1, $str2);
You could try using similar_text.
It can get quite slow with 20,000+ characters (3-5 seconds) but your example you mention using only sentences, this will work just fine for that usage.
One thing to note is when comparing string of different sizes you will not get 100%. For example if you compare "he" with "head" you would only get a 50% match.
I am using base36 to shorten URLs. I have an id of a blog entry and convert that id to base36 to make it smaller. Base36 only includes lowercase letters. How can I include uppercase letters? If I use base64_encode it actually makes the string longer.
you can find examples of source-code to create short-urls containing letters (both lower and upper case) and number on those two articles, for instance :
Create short IDs with PHP - Like Youtube or TinyURL
Building a URL Shortener
Here is the portion of code used in that second article (quoting) :
$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($codeset);
$n = 300;
$converted = "";
while ($n > 0) {
$converted = substr($codeset, ($n % $base), 1) . $converted;
$n = floor($n/$base);
}
echo $converted; // 4Q
And you can pretty easily encapsulate this in a function -- only thing to consider is that $n is to be received as a parameter :
function shorten($n) {
$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($codeset);
$converted = "";
while ($n > 0) {
$converted = substr($codeset, ($n % $base), 1) . $converted;
$n = floor($n/$base);
}
return $converted;
}
And calling it this way :
$id = 123456;
$url = shorten($id);
var_dump($url);
You get :
string 'w7e' (length=3)
(You can also add some other characters, if needed -- depending on what you want to get in your URLs)
Edit after the comment :
Reading through the second article (from which I got the shortening code), you'll find the code that does the un-shortening.
Encapsulating that code in a function shouldn't be that hard, and might get you something like this :
function unshorten($converted) {
$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($codeset);
$c = 0;
for ($i = strlen($converted); $i; $i--) {
$c += strpos($codeset, substr($converted, (-1 * ( $i - strlen($converted) )),1))
* pow($base,$i-1);
}
return $c;
}
And calling it with a shortened-url :
$back_to_id = unshorten('w7e');
var_dump($back_to_id);
Will get you :
int 123456
function dec2any( $num, $base=62, $index=false ) {
// Parameters:
// $num - your decimal integer
// $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62))
// $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu")
if (! $base ) {
$base = strlen( $index );
} else if (! $index ) {
$index = substr( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base );
}
$out = "";
for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) {
$a = floor( $num / pow( $base, $t ) );
$out = $out . substr( $index, $a, 1 );
$num = $num - ( $a * pow( $base, $t ) );
}
return $out;
}
Shamelessly borrowed from a commenter on PHP's base_convert() page (base_convert() only works up to base 32).