Stop giving error number_format for PHP - php

Here is question:
$var = 1000;
$var2 = number_format($var,2);// No error
And;
$var = 'Some String';
$var2 = number_format($var,2);// Gives 'number_format() expects parameter 1 to be double.... error'
My handling solution is;
$var = 'Some String';
$var_escape = 1000;
if(!$var2 = number_format($var,2)){
$var2 = $var_escape;// if $var not a integer; always give 1000 to $var2.
}
This solution working perfectly but; still giving "expect parameter error"; because of this line:
if(!$var2 = number_format($var,2)){
I don't want to use "#" supression. Is there any other solution for this issue? Thanks...
MY INSPIRED BY ANSWERS SOLUTION
if(!is_numeric($var2 = $var)){$var2 = $var_escape;}
Thanks all...

You can check if your input is a number or not using is_numeric function
$var = 'Some String';
$var_escape = 1000;
if(is_numeric($var))
$var2=number_format($var,2);
else
$var2=$var_escape;

You can simply just declare $var2 in advance with the default value, then check to ensure that incoming value of $var is numeric using the built-in is_numeric() function in PHP. If the incoming value of $var is indeed numeric, assign that numeric value to $var2, else $var2 will remain as the default 1000 as it's value.
$var2 = 1000;
if(is_numeric($var)){
$var2 = number_format($var,2);
}
// You can proceed to use $var2 here as it will be 1000 or the value from $var if it was numeric.

Be careful... Demo
Use:
if(is_float($var) || is_integer($var)){
Instead of:
if(is_numeric($var)){
Unless you want your numeric strings to be processed as well.

Using a regex will be the easiest, this verifies that it's either an integer or a float.
code
$vars = array(
'Some String',
123,
123.5,
-11,
"123.55",
"$2!!",
.1,
1,
".1",
"1"
);
foreach($vars as $var) {
if(0 !== preg_match('/^-?\d*\.?\d*$/', $var)) {
echo number_format($var, 2) . PHP_EOL;
} else {
echo $var . " -> " . 1000 . PHP_EOL;
}
}
output
Some String -> 1000
123.00
123.50
-11.55
123.55
$2!! -> 1000
0.10
1.00
0.10
1.00

Related

How to apply if condition when it's parameter is coming into a variable?

I have assigned a condition into a variable. Then I tried to put that variable as a parameter of a if statement. But the code is not working. Please check my code:
$a = 8;
$final_str = '$a == 10';
if($final_str) {
echo 'Output 1';
} else {
echo 'Output 2';
}
The desired output should be Output 2. But it is not working. I always see Output 1. Please help me in this case.
Thanks in advance!
As per your request, the real problem here is this line of code:
$final_str = '$a == 10';
Although you have said that you cannot change the first two lines of code as it is what you have intended, I think that what you have intended and the result of this are two different things.
You see, you are defining '$a == 10' which is interpreted literally as a string value.
So you are trying to do something like:
if ('some string') ...
The result of this is true because a string that is not empty is a truthy value.
I think your intention however, was to test if the variable $a is equal to the integer value of 10?
In which case you actually need to do:
$final_str = $a == 10;
The result of this can be true or false depending on whether the variable $a is equal to 10 or not, that way your if condition will reflect the desired result?
EDIT:
If however you are trying to create some PHP code dynamically within your string you'd need to run it through eval and here is more information relating to the usage.
EDIT 2:
I would rather try to re-factor this into something more like:
$thisPage = 8;
$truthyPages = array(10,20);
if (in_array($thisPage,$truthyPages)) {
echo 'positive output';
} else {
echo 'negative output';
}
Or maybe even:
$a = 8;
// Step 1
$final_result = $final_result || $a == 10;
// Step 2
$final_result = $final_result || $a == 20;
if ($final_result) {
echo 'success';
} else {
echo 'failure';
}

check php post value is numeric and well formatted

I need to check POST value is numeric and well formatted. My expected format is
number.number
1.0
11.5
If POST value comes without .(DOT) only 1 then I would want that php convert that to 1.0
I tried this code but it doesn't work.
$foo = '2';
$foo = preg_match('/\\d{2}\\:\\d{2}\\.\\d{2}/', $foo);
Thanks :)
Working code
//$value = '22';
$value = $_POST["input_value"];
if (is_numeric($value)) {
$new_value = number_format($value, 1);
} else {
$new_value = "$value is not numeric. <br>";
}
echo $new_value;
You basically want to check if the variable from the POST array is a float/double or not (float/double is a type of number in the format of x.x).
Cheking if a string is a float/double number
To do that, use this php built-in function: is_double or more accurate:is_float, that will tell you if the string is a float/double.
Checking if a string is an integer and converting it to a double/float value
If it's not a double, check if it's an integer (regular number): is_int, and if it's indeed an int, cast it to double by using number_format, look at the usage here: integer to double/float in php.
Example
$final_value;
$value = $_POST["wanted_value"];
if (is_float($value))
{
$final_value = $value;
}
else if (is_int($value))
{
$final_value = number_format($value, 1); // or 2 instead of 1 (2.0 or 2.00)
}
else
{
$final_value = "ERROR";
}
Hope this helps!

php reverse concatenation operator like .=

Don't think this exists but just want to make sure.
Is there a reverse for the .= operator in php.
example:
[$x .= $y] === [$x = $x.$y]
looking for:
[$x ? $y] === [$x = $y.$x]
No, there isn't.
The PHP manual documentation only lists two operators:
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
When you want to prepend to a string, just do $str = $add . $str. There is no need for a "special operator" here. If you use it frequently and don't want to retype it every time, you can create a function like this:
function prepend($text, $add) {
return $add . $text;
}
But, as you can probably guess, it's pointess.
Amal Murali's answer gave me an idea.
function p(&$x,$y){
$x = $y.$x;
return $x;
}
Now instead of having to type out;
$var1 = $var2 . $var1;
You can just do:
p($var1, $var2);
If you send the first variable as reference it does clean the code a bit.
Variables:
$var = ' world';
$var2 = 'Hello';
Usage
echo p($var, $var2);
or
p($var, $var2);
echo $var;
is now equal to:
$var = $var2 . $var1;
echo $var;

How do I convert a string to a number in PHP?

I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, cast it:
$num = "3.14";
$int = (int)$num;
$float = (float)$num;
There are a few ways to do so:
Cast the strings to numeric primitive data types:
$num = (int) "10";
$num = (double) "10.12"; // same as (float) "10.12";
Perform math operations on the strings:
$num = "10" + 1;
$num = floor("10.1");
Use intval() or floatval():
$num = intval("10");
$num = floatval("10.1");
Use settype().
To avoid problems try intval($var). Some examples:
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34 (octal as starts with zero)
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26 (hex as starts with 0x)
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
?>
In whatever (loosely-typed) language you can always cast a string to a number by adding a zero to it.
However, there is very little sense in this as PHP will do it automatically at the time of using this variable, and it will be cast to a string anyway at the time of output.
Note that you may wish to keep dotted numbers as strings, because after casting to float it may be changed unpredictably, due to float numbers' nature.
Instead of having to choose whether to convert the string to int or float, you can simply add a 0 to it, and PHP will automatically convert the result to a numeric type.
// Being sure the string is actually a number
if (is_numeric($string))
$number = $string + 0;
else // Let the number be 0 if the string is not a number
$number = 0;
Yes, there is a similar method in PHP, but it is so little known that you will rarely hear about it. It is an arithmetic operator called "identity", as described here:
Aritmetic Operators
To convert a numeric string to a number, do as follows:
$a = +$a;
If you want get a float for $value = '0.4', but int for $value = '4', you can write:
$number = ($value == (int) $value) ? (int) $value : (float) $value;
It is little bit dirty, but it works.
You can use:
(int)(your value);
Or you can use:
intval(string)
In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.
You can always add zero to it!
Input Output
'2' + 0 2 (int)
'2.34' + 0 2.34 (float)
'0.3454545' + 0 0.3454545 (float)
Just a little note to the answers that can be useful and safer in some cases.
You may want to check if the string actually contains a valid numeric value first and only then convert it to a numeric type (for example if you have to manipulate data coming from a db that converts ints to strings). You can use is_numeric() and then floatval():
$a = "whatever"; // any variable
if (is_numeric($a))
var_dump(floatval($a)); // type is float
else
var_dump($a); // any type
Here is the function that achieves what you are looking for. First we check if the value can be understood as a number, if so we turn it into an int and a float. If the int and float are the same (e.g., 5 == 5.0) then we return the int value. If the int and float are not the same (e.g., 5 != 5.3) then we assume you need the precision of the float and return that value. If the value isn't numeric we throw a warning and return null.
function toNumber($val) {
if (is_numeric($val)) {
$int = (int)$val;
$float = (float)$val;
$val = ($int == $float) ? $int : $float;
return $val;
} else {
trigger_error("Cannot cast $val to a number", E_USER_WARNING);
return null;
}
}
If you want the numerical value of a string and you don't want to convert it to float/int because you're not sure, this trick will convert it to the proper type:
function get_numeric($val) {
if (is_numeric($val)) {
return $val + 0;
}
return 0;
}
Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>
Source: https://www.php.net/manual/en/function.is-numeric.php#107326
I've been reading through answers and didn't see anybody mention the biggest caveat in PHP's number conversion.
The most upvoted answer suggests doing the following:
$str = "3.14"
$intstr = (int)$str // now it's a number equal to 3
That's brilliant. PHP does direct casting. But what if we did the following?
$str = "3.14is_trash"
$intstr = (int)$str
Does PHP consider such conversions valid?
Apparently yes.
PHP reads the string until it finds first non-numerical character for the required type. Meaning that for integers, numerical characters are [0-9]. As a result, it reads 3, since it's in [0-9] character range, it continues reading. Reads . and stops there since it's not in [0-9] range.
Same would happen if you were to cast to float or double. PHP would read 3, then ., then 1, then 4, and would stop at i since it's not valid float numeric character.
As a result, "million" >= 1000000 evaluates to false, but "1000000million" >= 1000000 evaluates to true.
See also:
https://www.php.net/manual/en/language.operators.comparison.php how conversions are done while comparing
https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion how strings are converted to respective numbers
In addition to Boykodev's answer I suggest this:
Input Output
'2' * 1 2 (int)
'2.34' * 1 2.34 (float)
'0.3454545' * 1 0.3454545 (float)
Only multiply the number by 1 so that the string is converted to type number.
//String value
$string = "5.1"
if(is_numeric($string)){
$numeric_string = $string*1;
}
Alright so I just ran into this issue. My problem is that the numbers/strings in question having varying numbers of digits. Some have no decimals, others have several. So for me, using int, float, double, intval, or floatval all gave me different results depending on the number.
So, simple solution... divide the string by 1 server-side. This forces it to a number and retains all digits while trimming unnecessary 0's. It's not pretty, but it works.
"your number string" / 1
Input Output
"17" 17
"84.874" 84.874
".00234" .00234
".123000" .123
"032" 32
Here is a function I wrote to simplify things for myself:
It also returns shorthand versions of boolean, integer, double and real.
function type($mixed, $parseNumeric = false)
{
if ($parseNumeric && is_numeric($mixed)) {
//Set type to relevant numeric format
$mixed += 0;
}
$t = gettype($mixed);
switch($t) {
case 'boolean': return 'bool'; //shorthand
case 'integer': return 'int'; //shorthand
case 'double': case 'real': return 'float'; //equivalent for all intents and purposes
default: return $t;
}
}
Calling type with parseNumeric set to true will convert numeric strings before checking type.
Thus:
type("5", true) will return int
type("3.7", true) will return float
type("500") will return string
Just be careful since this is a kind of false checking method and your actual variable will still be a string. You will need to convert the actual variable to the correct type if needed. I just needed it to check if the database should load an item id or alias, thus not having any unexpected effects since it will be parsed as string at run time anyway.
Edit
If you would like to detect if objects are functions add this case to the switch:
case 'object': return is_callable($mixed)?'function':'object';
$a = "10";
$b = (int)$a;
You can use this to convert a string to an int in PHP.
I've found that in JavaScript a simple way to convert a string to a number is to multiply it by 1. It resolves the concatenation problem, because the "+" symbol has multiple uses in JavaScript, while the "*" symbol is purely for mathematical multiplication.
Based on what I've seen here regarding PHP automatically being willing to interpret a digit-containing string as a number (and the comments about adding, since in PHP the "+" is purely for mathematical addition), this multiply trick works just fine for PHP, also.
I have tested it, and it does work... Although depending on how you acquired the string, you might want to apply the trim() function to it, before multiplying by 1.
Late to the party, but here is another approach:
function cast_to_number($input) {
if(is_float($input) || is_int($input)) {
return $input;
}
if(!is_string($input)) {
return false;
}
if(preg_match('/^-?\d+$/', $input)) {
return intval($input);
}
if(preg_match('/^-?\d+\.\d+$/', $input)) {
return floatval($input);
}
return false;
}
cast_to_number('123.45'); // (float) 123.45
cast_to_number('-123.45'); // (float) -123.45
cast_to_number('123'); // (int) 123
cast_to_number('-123'); // (int) -123
cast_to_number('foo 123 bar'); // false
function convert_to_number($number) {
return is_numeric($number) ? ($number + 0) : FALSE;
}
You can use:
((int) $var) ( but in big number it return 2147483647 :-) )
But the best solution is to use:
if (is_numeric($var))
$var = (isset($var)) ? $var : 0;
else
$var = 0;
Or
if (is_numeric($var))
$var = (trim($var) == '') ? 0 : $var;
else
$var = 0;
Simply you can write like this:
<?php
$data = ["1","2","3","4","5"];
echo json_encode($data, JSON_NUMERIC_CHECK);
?>
There is a way:
$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);
Using is_* won't work, since the variable is a: string.
Using the combination of json_encode() and then json_decode() it's converted to it's "true" form. If it's a true string then it would output wrong.
$num = "Me";
$int = (int)$num;
$float = (float)$num;
var_dump($num, $int, $float);
Will output: string(2) "Me" int(0) float(0)
Now we are in an era where strict/strong typing has a greater sense of importance in PHP, I use json_decode:
$num = json_decode('123');
var_dump($num); // outputs int(123)
$num = json_decode('123.45');
var_dump($num); // outputs float(123.45)
You can change the data type as follows
$number = "1.234";
echo gettype ($number) . "\n"; //Returns string
settype($number , "float");
echo gettype ($number) . "\n"; //Returns float
For historical reasons "double" is returned in case of a float.
PHP Documentation
If you don't know in advance if you have a float or an integer,
and if the string may contain special characters (like space, €, etc),
and if it may contain more than 1 dot or comma,
you may use this function:
// This function strip spaces and other characters from a string and return a number.
// It works for integer and float.
// It expect decimal delimiter to be either a '.' or ','
// Note: everything after an eventual 2nd decimal delimiter will be removed.
function stringToNumber($string) {
// return 0 if the string contains no number at all or is not a string:
if (!is_string($string) || !preg_match('/\d/', $string)) {
return 0;
}
// Replace all ',' with '.':
$workingString = str_replace(',', '.', $string);
// Keep only number and '.':
$workingString = preg_replace("/[^0-9.]+/", "", $workingString);
// Split the integer part and the decimal part,
// (and eventually a third part if there are more
// than 1 decimal delimiter in the string):
$explodedString = explode('.', $workingString, 3);
if ($explodedString[0] === '') {
// No number was present before the first decimal delimiter,
// so we assume it was meant to be a 0:
$explodedString[0] = '0';
}
if (sizeof($explodedString) === 1) {
// No decimal delimiter was present in the string,
// create a string representing an integer:
$workingString = $explodedString[0];
} else {
// A decimal delimiter was present,
// create a string representing a float:
$workingString = $explodedString[0] . '.' . $explodedString[1];
}
// Create a number from this now non-ambiguous string:
$number = $workingString * 1;
return $number;
}
All suggestions lose the numeric type.
This seems to me a best practice:
function str2num($s){
// Returns a num or FALSE
$return_value = !is_numeric($s) ? false : (intval($s)==floatval($s)) ? intval($s) :floatval($s);
print "\nret=$return_value type=".gettype($return_value)."\n";
}
//Get Only number from string
$string = "123 Hello Zahid";
$res = preg_replace("/[^0-9]/", "", $string);
echo $res."<br>";
//Result 123

PHP Datatype mismatch on comparison

So I have 2 variables, var1, var2.
$var1 = "53,000,000" //- integer
$var2 = 10 //- string
In the end I want to compare both, so I
$var1 = (int)str_replace(",","",$var1); // => 53000000 - integer
Here's my issue .. if I do:
if($var1 > $var2)
$var2 = $var1
I get $var2 = 0 .... Why ?
.. running on PHP 5.2.14
EDIT Accidentally typed in substr_replace instead of str_replace. Updated.
I had to add a couple semicolons, but here's the code:
$var1 = "53,000,000"; //- integer
$var2 = 10; //- string
//In the end I want to compare both, so I
$var1 = (int)str_replace(",","",$var1); // => 53000000 - integer
//Here's my issue .. if I do:
if($var1 > $var2)
$var2 = $var1;
var_dump($var1, $var2);
And here's my output:
int(53000000) int(53000000)
I used 5.2.6, but it shouldn't matter. Do you have any other code in between what you're showing?
Use str_replace() instead of substr_replace().
You've specified the wrong parameters for substr_replace, so $var1 is evaluated to 0. I guess you wanted to use str_replace.
No need for type casting. just do the str_replace
Here is code
$var1 = "53,000,000" ;
$var2 = 10;
$var1=str_replace(',','',$var1);
if($var1 > $var2)
$var2 = $var1;
echo $var2;

Categories