When I change the string into float I always get 0 - php

I am trying to convey $string to float. The type of $string is string in the format of "0.0111455667". I have the following code in php.I have tried all these methods and I got 0 for all of them. how can I convert the string to float?why I always get 0?
PS: please do not assume my question as duplicate, I have already tried all the methods in the similar questions and none of them worked for me.
$float = (float) $string;
//$float2 = $string + 0.0; //this works as well.
$floatval = floatval($string);
$double = (double) $string;
// TEST
echo $string;
echo $float;
//echo $float2;
echo $floatval;
echo $double;

Your problem is the content of $string.
In PHP, every time you convert a string to a float, be it by casting (float) $string, or floatval($string), you will always get 0 if the first character of the string is not numeric.
From PHP docs: String conversion to numbers
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero)
Double-check the content of $string. Probably you have some spurious characters at its beginning.

Related

How can I convert this string into a human readable IP address in PHP?

I've got a string representing an IPv4 address:
$ip = '\x7F\0\0\x01';
When I try to pass that to inet_ntop($ip) it's giving me grief:
PHP Warning: inet_ntop(): Invalid in_addr value
If I declare the variable manually using double quotes it works:
$ip = "\x7F\0\0\x01";
inet_ntop($ip); // "127.0.0.1"
However, I am not declaring these variables manually. I'm working with what is given to me in an object.
How can I convert '\x7F\0\0\x01' into a string that inet_ntop() will accept?
In other words, how can I make PHP parse a string literally as if I were manually declaring it with double quotes?
Some interesting facts:
gettype('\x7F\0\0\x01'); // string
gettype("\x7F\0\0\x01"); // string
ord('\x7F\0\0\x01'); // 92
ord("\x7F\0\0\x01"); // 127
implode(unpack('H*', '\x7F\0\0\x01')); // 5c7837465c305c305c783031
implode(unpack('H*', "\x7F\0\0\x01")); // 7f000001
mb_detect_encoding('\x7F\0\0\x01'); // ASCII
mb_detect_encoding("\x7F\0\0\x01"); // UTF-8
"\x7F\0\0\x01" == '\x7F\0\0\x01'; // false
// and for the haters
long2ip('\x7F\0\0\x01'); // PHP Warning: long2ip() expects parameter 1 to be integer, string given
One possibility is to parse the string into its component pieces (starting with \); convert them to the decimal equivalent and use chr to get back the original characters. These can then be joined into a string which is suitable for inet_ntop:
$ip = '\x7F\0\0\x01';
preg_match_all('/\\\x?([\dA-F]+)/', $ip, $parts);
$ip = implode('', array_map(function ($v) { return chr(hexdec($v)); }, $parts[1]));
echo inet_ntop($ip);
Another alternative is to use pack, after stripping out the \x parts and replacing \0 with 00:
$ip = '\x7F\0\0\x01';
$ip = pack('H*', str_replace(array('\x', '\0'), array('', '00'), $ip));
echo inet_ntop($ip);
In both cases the output is:
127.0.0.1
Demo on 3v4l.org
The problem is that you've got the literal ASCII output of a binary string and not the real binary value you expect it to be. I'm not sure how you got the literal ASCII value. There is a way to convert it, but you're not going to like it.
You can use eval() to accomplish what you're trying to do. All arguments for eval() being evil still apply.
$ip = '\x7F\0\0\x01';
eval("\$ip = \"$ip\";");
echo inet_ntop($ip);
This will print out 127.0.0.1.
Since binary doesn’t always result in literal ASCII characters, I worry you’ll see literal characters like � in the strings, and these won’t convert properly to the binary value you expect them to be.
For example, here are the characters printed to screen in Psysh:
>>> hex2bin('7f000001') // This is 127.0.0.1
=> "\x7F\0\0\x01"
>>> hex2bin('ffffffff') // This is 255.255.255.255
=> b"ÿÿÿÿ"
The first value looks familiar, right? That's the string literal that we can convert back into a binary string using eval(), like we did in the example above. But the binary value for ffffffff is a different story. If we try to convert it, it doesn't give us the 255.255.255.255 value we expect.
$ip = 'ÿÿÿÿ';
eval("\$ip = \"$ip\";");
echo inet_ntop($ip);
In this case, inet_ntop() returns false, but we know it should work:
>>> inet_ntop(hex2bin('ffffffff'));
=> "255.255.255.255"
So, I worry that any attempt to convert these values from string literals into binary strings is not going to work in all cases, whether using eval() or any of the other answers provided here.
However, if everything is coming to you in the format \0\0\0\0, where each "segment" is either a zero or a hex value in the format x00, then you should be in good shape, because these are the same:
>>> "\xFF\xFF\xFF\xFF"
=> b"ÿÿÿÿ"
You can make your own function like this
function convertStringToInAddr(string $string) {
$return = null;
$exploded = explode("\\", $string);
foreach($exploded as $hex) {
if( $hex != "" ) {
$return .= chr(hexdec(str_replace("x", "", $hex)));
}
}
return $return;
}

PHP - differentiate values from hexadecimal to string

I have a string which value is 123, like: $string = '123'; and my hex value, which is $hex = bin2hex($string); and the return is 313233. When i convert to string again, using hex2bin(), it returns 123 correctly. But when i try to make a "compare" it always returns both like a hexadecimal value.
I know that each number, both 1, 2 and 3 are part of hexadecimal table, but, is there a way that can i differentiate each one ? I'd already searched something about it, but i got no solution.
I'm sorry if this question is poor. But it will really helped me. Besides, it's a doubt that i have.
My php code:
<?php
$string = '123';
$hex = bin2hex($string);
if(hex2bin($hex)){
echo 'hex';
}else{
echo 'not hex';
}
?>
As far as I understand, you are looking for the ctype_xdigit() function, which returns true if all the individual letters in your string are hexadecimal digits, otherwise false.
You just have to pass the string as a parameter:
if (ctype_xdigit($hex_string)){
echo 'hex';
} else {
echo 'not hex';
}
What you did in your original code was converting binary numbers to hexadecimals and then the other way round. It's no surprise that it didn't give you the expected results, as 123 is not a binary number, in the input there couldn't be any other digits than 0 and 1.
firstly, functions don't work as you think they do, i.e. if(hex2bin($hex)) is kind of nonsense when used like that. (it returns "123" which will always evaluate as "true")
secondly, consider using ctype_xdigit which does what you want
<?php
$string = '123';
$hex = bin2hex($string);
if(ctype_xdigit($hex)){
echo 'is a hex value (was originally '+hex2bin($hex)+')';
}else{
echo 'not hex';
}
?>

PHP Strip String, Convert to int

I have a STRING $special which is formatted like £130.00 and is also an ex TAX(VAT) price.
I need to strip the first char so i can run some simple addition.
$str= substr($special, 1, 0); // Strip first char '£'
echo $str ; // Echo Value to check its worked
$endPrice = (0.20*$str)+$str ; // Work out VAT
I don't receive any value when i echo on the second line ? Also would i then need to convert the string to an integer in order to run the addition ?
Thanks
Matt
+++ UPDATE
Thanks for your help with this, I took your code and added some of my own, There are more than likely nicer ways to do this but it works :) I found out that if the price was below 1000 would look like £130.00 if the price was a larger value it would include a break. ie £1,400.22.
$str = str_replace('£', '', $price);
$str2 = str_replace(',', '', $str);
$vatprice = (0.2 * $str2) + $str2;
$display_vat_price = sprintf('%0.2f', $vatprice);
echo "£";
echo $display_vat_price ;
echo " (Inc VAT)";
Thanks again, Matt
You cannot use substr the way you are using it currently. This is because you are trying to remove the £ char, which is a two-byte unicode character, but substr() isn't unicode safe. You can either use $str = substr($string, 2), or, better, str_replace() like this:
$string = '£130.00';
$str = str_replace('£', '', $string);
echo (0.2 * $str) + $str; // 156
Original answer
I'll keep this version as it still can give some insight. The answer would be OK if £ wouldn't be a 2byte unicode character. Knowing this, you can still use it but you need to start the sub-string at offset 2 instead of 1.
Your usage of substr is wrong. It should be:
$str = substr($special, 1);
Check the documentation the third param would be the length of the sub-string. You passed 0, therefore you got an empty string. If you omit the third param it will return the sub-string starting from the index given in the first param until the end of the original string.

PHP Multiplication not working

$databtcguild = file_get_contents('http://btcguild.com');
preg_match('~<b>Pool Speed</b></a> (.*?) TH/s~',$databtcguild,$btcguild);
$btcguildhashrategh = ($btcguild[1] * 1000);
echo $btcguildhashrategh;
echo "<br>";
echo $btcguild[1];
For some reason this code is outputting the wrong answer. For example, $btcguild[1] will equal 12,747 and this code will output 12000. I'm completely lost here. Thanks for any help.
The "hash speed" value you are extracting from that site has a value with a comma in it:
12,747
PHP needs to convert this string to a numeric value, and the comma causes the numeric value 12 to be returned (, is interpreted as a decimal)
Make sure you strip all non-numeric characters before multiplying:
//keep only values 0-9 and decimal (period)
$hash_speed = preg_replace("/[^0-9.]/", "", $btcguild[1]);
$btcguildhashrategh = ($hash_speed * 1000); //returns 12747000
Try explicitly type-casting the result: $btcguildhashrategh = ((double)$btcguild[1] * 1000);
Otherwise PHP will convert it into an int.

Why it's 0 but not 255 here?

echo intval(chr(255));
I don't understand...
The chr() function turns a byte into its ASCII equivalent and intval() function gets the integer value of a variable.
If we were to break the statement into two different lines, this would be:
$a = chr(255); // $a is now a string
echo intval($a);
If you check intval()'s documentation you will notice that:
Strings will most likely return 0
although this depends on the leftmost
characters of the string. The common
rules of integer casting apply.
That's why the result is zero.
The byte 0xFF does not represent a digit in either octal, decimal or hexadecimal what intval is looking for. You probably wanted the ord function.
To output 255, you need:
echo intval(ord(chr(255)));
There are 128 ordinal numbers in ASCII, the 255 comes out to be ÿ so when you convert it to a number with intval, it will be 0.
Because chr delivers a string, in this case with just one character, the character 0xFF, or better known as ÿ.
intval on the other hand does a conversion from a string to an integer based on the content of the string, and not the characters.
echo intval("33"); // will print 33
echo intval("10", 8); // will print 8
echo intval("0xFF", 16); // will print 255
echo intval("m"); // will print zero...
//you can't convert letters like that to numbers.
chr(255)
returns a character corresponding to ASCI 255
and intval try to bring out integer part from a variable
since chr(255) returns a non-numeric character so intval get no int value and return 0

Categories