When i try to add a integer to 3 digit number formed using php number_format() function give right result but when number become 4 digit it give wrong output.
I have tried this. please explain me the reason behind this??
$num1=number_format(1000.5,2);
$num1+=1;
echo $num1;
Output:2
But
$num1=number_format(100.5,2);
$num1+=1;
echo $num1."\n";`
Output:101.5
number_format() returns a string not a number. It is there to format a numeric type (integer, float) to a string with a specific, desired "layout". So what you do is add the number 1 to the string resulting from number_format, which will try to cast the string back to a number, apparently resulting in 1 for the string cast as well, which gives you 2 total.
tl;dr; Do calculations on numbers only and then do number_format at the very end to output in a defined format.
$num1 = number_format(1000.5, 2);
var_dump($num1);
// => string(8) "1,000.50"
$num1 += 1;
var_dump($num1);
// => int(2)
Function number_format() returns string.
And that string is type cast to integer when you are adding 1
See Type Juggling
The quickest solution would be using str_replace() on your formatted number.
Something like this would do:
(float)str_replace( ',', '', $formatted_number )
By removing the commas from the string and asking for the float value, you'll get a usable number.
Related
I read some data from a csv file. Each line in the file has a float value. these values can be either:
.123 : starting with a period, so I need to add a zero before.
1,23: having a delimter comma ',' instead of period so I need to change that.
1.2e3 having an exponential-format so I need to convert it to decimal format.
I can't use the function number_format because I can't set the number of decimal points (the float numbers don't have a fixed length of the decimal part and we want to take them as they are to not lose data).
Here is what I tried so far; I built two functions, the first one filters the floats, the second one corrects them when the filter returns false:
function validateFloat($float){
if(!filter_var($float,FILTER_VALIDATE_FLOAT,array('flags' => FILTER_FLAG_ALLOW_FRACTION))){
return false;
}
}
function correctFloat($float){
if (validateFloat($float)==false){
$number = number_format($float,null,'.');
str_replace($number,'',$line);
}
}
I don't know how to build the correctFloat function. Any suggestions ? Appreciate it.
Your function can check if there is a comma and get the correct deliminator then use floarval on any other case
function change_format($value){
if(is_string($value)){
//has to be a string if using ','
$value= str_replace(",",".",$value);
}
return floatval($value);
}
echo change_format(.123) ."<br>";
echo change_format("1,23") ."<br>";
echo change_format("1.2e3");
Outputs:
0.123
1.23
1200
DateTime object outputs 01, 02, 03 etc when I
use
$num = $dt->format('d');
to get the day number
Then I compare the $num value if it's
the first day of the month like so:
if ($num == 1)
but the $num value is '01'.
Now php compares it as expected
var_dump($num == 1)
returns true
I was thinking, should this be enough for me
or I should enclose the $num variable with an intval
like so:
intval($num)
this way if it is 01 it will display '1'
Basically $num = $dt->format('d') returns a String.
If you have == as a Comparison Operators and the two values are not from the same data type, PHP try to match them.
So in your case ($num == 1) you are comparing a String with a literal Integer
Therefore PHP is trying to converting the Sting into a Integer (only for the comparison).In the end you are already comparing two Integers.
The type conversion does not take place when the Comparison Operator is === or !== as this involves comparing the type as well as the value.So with $num = '1';, a comparison like $num === 1 would always return false.If you like to strip of leading zeros but don't convert the data type, I would use: $num_as_str = ltrim($num,'0');
If you like to convert the variable to an Integer use this:
$num_as_int = intval($num);
From the PHP manual:
String conversion to numbers
When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise it will be evaluated as an integer.
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). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
Everything written by Webdesigner is right, but you can simply get the day number without leading zero by 'j' parameter:
$num = $dt->format('j');
So you can compare it with an ordinary numbers without any explicit type cast.
I have a url that will look as follows.
post/:id
I am exploding the $_SERVER['REQUEST_URI'];
and I need to make the $uri[2] is numerical so I can do things like
$next = $uri[2]++;
I have tried is_numeric but of course the request_uri is a string (broken into an array of strings).
Can I type cast in php to integer?
$int = (int) $uri[2];
You just have to convert from string to integer.
Have you tried intval(): http://php.net/manual/en/function.intval.php?
int intval(mixed $var [, int $base = 10 ])
"Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1."
UPDATE
Having wondered what the difference between (int) $string and intval($string) is, there are some interesting comments on previous SO questions;
(int) is upto 600% faster
intval makes it easier to typecast within other functions
intval has the benefit of changing base (although this is fairly obscure)
intval is more readable (tho this is obviously very subjective)
Is there any particular difference between intval and casting to int - `(int) X`?
When should one use intval and when int
http://hakre.wordpress.com/2010/05/13/php-casting-vs-intval/
Just to clarify both David and ChrisW are correct. Those are two ways of doing it as described at http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting
<?php
$str = '100';
var_dump( $str ); // string(3) "100"
// http://php.net/manual/en/function.intval.php
var_dump( intval($str) ); // int(100)
// http://php.net/manual/en/language.types.type-juggling.php
var_dump( (int) $str ); // int(100)
?>
you can just take it as a number from url passing argument in as a $_GET request.
Or pass through as a $_POST request.
But in the case of $_POST request we cann't pass the value to url. if you want you can using $_SERVER['REQUEST_URI'] and convert to (int) $_GET['pid'].
if($_GET['choice'] == (int))
or
if($_GET['choice'] == (string))
I got an error.
All GET parameters are strings. If you want to be certain that it's an integer in the string then you should sanitize it.
To check if the string $_GET['choice'] may be represented as an integer, use ctype_digit(), eg
if (ctype_digit($_GET['choice'])) {
// integer
}
You're doing it wrong. Your example shows CASTING:
$var = (int)"15"; // casts the string 15 as an integer
If you want to compare if something is an INTEGER, you can use the is_int() function in PHP. There are other operators that will do this for strings, arrays, etc;
http://us2.php.net/manual/en/function.is-int.php
What will the following code print?
print ‘’four’’ * 200;
It prints "0"
alt text http://mywebprogrammer.com/images/soAnswer.PNG
The result is to the left of the second line.
To see why this is you can do a quick test echo (int)'four'; this will attempt to explicitly cast the string 'four' to an integer which since it is not an integer will technicaly fail, resulting in a 0 which of course is equal to FALSE. If you replace the 'four' with '4', still a string, you can properly cast it to an integer and it will produce the result of 800 in the case of your example ("print '4' * 200").
Yes it would print zero "0" indeed. The thing is PHP will type cast the string value to an integer. This would result in 0 (Zero); and if you times any value with zero you'll get zero.
Good Question Roland!
Since the string cannot be casted to a number, the multiplication with a string will result in 0.