Never had to do such a basic thing before. How do I initialize a variable as a float before doing logic? Do either of these examples make sense?
$var = 0.0;
$var = (float) 0;
Both make sense, the first is shorter, with the second you can initialized with a dynamic value, your choice !
EDIT : But I agree with #Niet the Dark Absol, it poorly matters since you use test function such as ctype_digit, or is_numeric.
from http://php.net/manual/en/language.types.float.php
Floating point numbers (also known as "floats", "doubles", or "real
numbers") can be specified using any of the following syntaxes:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
so defining a float by using $var = 0.0 is correct. While casting is not technically incorrect I don't believe it's something you should use when you don't need to.
Try to use number_format.
For example:
$number = 20;
echo number_format($number,2) // will output 20.00
// number_format($number,$decimals,$dec_point,$thousands_sep)
Related
Firstly, let's say for the sake of argument, the reasons why I want to do this is arbitrary and not solution specific.
I would like to explicitly cast a variable, regardless of input, and increment it after typecasting, not with the original variable. For example, not like this:
$num = "47 downvotes";
(int) ++$num;
I am looking for something similar to this psuedo-coded version, or a variation thereof:
$num = "value";
++((int) $num);
For PHP being loose, I was really hoping this to work, but I can't use the Pre-increment operator without creating another variable first.
$num = "value";
$cast = (int) $num;
echo ++$cast;
While testing, I found that PHP is loose enough for it to work by adding a digit however:
$num = "47 dogs";
echo ((int) $num) + 1;
I also understand my first example, isn't wrong, but again, for arbitrary reasons, I need to make sure it has been casted prior to incrementing/decrementing.
So the question is, why is PHP loose enough for the latter to compile?
If you could provide resources or links to any reputable reading material I would appreciate that as well.
With explicit typecasting you have to assign the result to a variable. In your examples, you are trying to increment variables when they are strings, which fails or doesn't produce the result you expect in combination with typecasting.
Look at your original example:
<?php
$num = "47 downvotes";
echo $num . PHP_EOL;
echo ++$num;
The result of incrementing a string isn't what you expect it to be:
47 downvotes
47 downvotet
So your original supposition is that PHP doesn't work when in fact it does.
$num = "47 downvotes";
echo (int) ++$num . PHP_EOL;
$num2 = "47";
echo (int) ++$num2;
Output:
47
48
The process of typecasting is inherently complicated, and has all sorts of behavior that can produce unexpected results, and just isn't the catchall dependable "fix your input" that will let you find the numeric portion of any string available to you in a single line of code, but that doesn't mean that PHP is flawed.
I have a variable $var1 = "21,855.00". I already tried using preg_replace and str_replace but I could not really achieve what I was looking for.
I wish to echo it as 21855. How can I do that using PHP?
Use intval()
$var1 = 21855.00;
$varInt= intval($var1);
You can also do
$varInt= (int)$var1;
You can also use floor() to round down
$varInt= floor($var1);
You can also use ceil() to round up
$varInt= ceil($var1);
You can also do
settype($var1, "integer");
haha i must be having a lot of time to waste today :)
Just taking note:
If its a literal string like:
$var1 = '21,855.00'; // string(9) "21,855.00"
You can also do it this way:
$var1 = '21,855.00';
$var2 = filter_var(strtok($var1, '.'), FILTER_SANITIZE_NUMBER_INT);
echo $var2; // 21855
Sample Output
Or with regex:
$var1 = '21,855.00';
$var2 = (int) preg_replace('/(?<=\d),(?=\d{3}\b)/','', $var1);
var_dump($var2); // int(21855)
You can do it in different ways;
$myFloat = 123456.78;
$firstWay = intval($myFloat);
$secondWay= (int) $myFloat;
You can use intval() as Hanky stated or cast the value to integer with using (int). I believe using (int) $myFloat is faster than using intval($myFloat)
You can try with this also -
$var1 = (int) 21855.00;
You could try intval()
eg:
$val = 21855.00;
$val_int = intval($val);
I'm trying to get the fractional number count of a decimal number. I tried following simple code, but the loop runs forever.
$var = 123.456;
$fraction_count = 0;
echo $var, "<br>";
while (is_double($var)) {
$var *= 10;
$fraction_count++;
echo $var, "<br>";
}
I'm new to php so, forgive me if this is a stupid question!
Floating point numbers are not trivial to deal with (see the manual for more information). But you don't even need to deal with the number as such.
If you treat it as a string, you can explode() on the . and use strlen() on the second part to get the $fraction_count:
$var = 123.456;
$parts = explode('.', $var);
$fraction_count = strlen($parts[1]);
Since PHP doesn't save trailing 0s on numbers, this will work for 123.4560 as well, but be sure to input it as a number, "123.4560" will get you a wrong result.
I had this question in my mind for some time. Say we have a variable:
$foo = $_GET['value']; (this is a generical example)
I wanted to know if PHP has something similar to Lua where you can have something like:
local randomvar = "string";
local foo = randomvar or 0;
This way, foo would be considered integer and if randomvar is not an integer, the value 0 will be assigned to it.
Yes, there is method is_numeric
<?
$foo = "S";
$bar = (is_numeric($foo)) ? $foo:0;
echo $bar;
?>
Please consider going through docs for your purpose http://php.net/manual/en/function.is-numeric.php
You can cast it's type:
$foo = (int) $_GET['value'];
That wouldn't set it to 0. but it would definitely remove non-numeric characters.
Or you can use is_int():
function stringToZero($var) {
return (is_int($_GET['value'])) ? $var : 0;
}
$temp = $_GET['value']; // because I'm not sure it's correct to send a $_GET to a function. might not be necessary.
$randomvar = stringToZero($temp);
unset($temp);
Consider the below code in PHP
$a = 8425996523 * 121212713;
$b = sprintf('%.2f', $a);
$mul = gmp_mul("8425996523", "121212713");
Output is
1.0213378982814E+18
1021337898281396864.00
1021337898281396899
The actual answer is 1021337898281396899. Hence, it is clear that we need to use any libraries like gmp_mul to do arithmetic with large numbers.
My question is, how to identify such errors?
ie, when PHP does a calculation like
8425996523 * 121212713
, how can I identify that the result is not correct?
One way I see is to check for E and assume that whenever we forcefully convert such numbers, the errors exits.
Use
$b = sprintf('%.2d', $a);
Instead of
$b = sprintf('%.2f', $a);
Here's a screenshot of the source code to show the difference: