issue in reversly printing a number in php [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does a leading zero do for a php int?
I am just a beginner in php. I tried to write program for print the given number as reverse. For example if i use 123 as input the result should be 321. I tried the following code. It works fine. But if the given input is 0123 the output is 38. I couldn't correct it. How can i correct my code? here is my code.
<?php
$n=123;
$b=0;
while($n>=1)
{
$b=$b*10+$n%10;
$n=$n/10;
}
echo $b;
?>

When you add a 0 to the beginning of your number, PHP treats the number as octal.
Octal 123 is decimal 83, which correctly changes to 38.

Just use the dynamic nature of PHP not much caring about the difference between numbers and strings:
echo strrev(123);
http://www.php.net/manual/en/function.strrev.php

Yes, it's because the numbers that are starting with 0 are considered in base 8, so 0123 is in fact 83 in base 10.
So, your algorithm is correct for integer numbers - if you want the revert of 0123 to be 3210, you could simply revert it as a string and you can simply use the strrev function

I think your math is the problem. You should have parenthesis around the multiplier and mod.
<?php
$num=6541020;
$revnum=0;
do{
$revnum=($revnum *10)+($num % 10);
$num=(int)($num / 10 );
}while($num>0);
echo $revnum;
?>
http://www.weberdev.com/get_example.php3?ExampleID=4879

you could use something like this:
<?php
$rprint = function ($nr) use (&$rprint)
{
echo $nr%10;
if($nr > 10)
{
$rprint($nr/10);
}
};
$rprint(12364);
?>
Edit 1:
OR you could use strings instead of numbers. As I suppose it was already suggested.
(I was a bit out of the subjects)

the integer with the leading zero is always treated as octal in php. So just make it as a string and use the buitin php function strrev()

Related

How does base_convert () create a random character string in php?

I am learning php myself with short exercises and I came through this small excercise to generate random 11 character string
public function Random_string()
{
$number = rand(10e12, 10e16);
echo base_convert($number, 10, 36);
//Sample output=9n4jfyh18v9
}
I thought the function generated string itself but when i use following values then it does not generate any string.
<?php
$number = "0977567";
echo base_convert($number,8,10);
//output=32631
?>
As far as i know rand() function generates random numbers while base_convert() function converts a number from one number base to another. In this process how does a string gets generated? It was very hard for me to understand this. It would be very nice if some could shed light on it. Thank you.
P.S. The first function shows error in PHP 7 but it completely works in PHP 5
You are right, rand(int $min, int $max) generates a random integer number between $min and $max, see documentation.
And base_convert(string $num, int $from_base, int $to_base) converts $num from $from_base to $to_base, but $num here is a string, because hexadecimal and other numbers above base 10 can contain characters as well, not only numbers, see documentation. That's also the reason why this functions returns a string, even if in some cases it won't actually contain any letters.
PHP also converts string to number if needed, for example next code will output 124 as int:
$a = "123";
var_dump($a+1);
In your first example, even if $number is an integer, PHP does the favour for you that it converts it into string, when you invoke base_convert from base 10 to 36.
In your second example, there is a problem, because the input $number="0977567" contains digit 9, and you want to convert it from base 8 to 10. But digit 9 does not exist in a base 8 number, only digits from 0 to 7. In this case PHP ignores invalid character 9, and converts only 077567 from base 8 to base 10, which happens to be 32631.
Please always check PHP warnings to catch issues like this. While learning and testing it is a good idea to set error_reporting(E_ALL); so you will get every message. Check documentation.

php scientific notation format

Trying to format a scientific number in PHP:
sprintf(%'1.2E',$var)
This gets me to 5.01E+1
I am trying to print 2 digits after the + sign
The parser requires the number format to be:
5.01E+01 instead of 5.01E+1
Is it possible to achieve this format with sprintf?
Is there any other method that can achieve this?
Thanks for looking
I couldn't find a way to do it solely with sprintf but I believe the following would be closer to the "correct" way to do it. The following calculates the exponent from the base-10 logarithm.
You can then pass the original value (dividing by 10 to the power of the exponent) and the exponent to the sprintf function as a float and an integer respectively. You can force the positive + sign remembering that it counts towards the character / padding length.
function scientificNotation($val){
$exp = floor(log($val, 10));
return sprintf('%.2fE%+03d', $val/pow(10,$exp), $exp);
}
demo / test cases :
scientificNotation(5.1); // 5.10E+00
scientificNotation(50.1); // 5.01E+01
scientificNotation(500.1); // 5.00E+02
scientificNotation(0.0051); // 5.10E-03
There is no built-in method as far as I know. But with a little bit of Regex black magic you can do something like this:
preg_replace('/(E[+-])(\d)$/', '${1}0$2', sprintf('%1.2E',$var));
Notice that I just wrapped your call to sprintf() with an appropriate call to preg_replace(). If the regular expression does not match it will leave the output from sprintf() as is.
The above answers both work great.
Also found out I can use:
$var_formatted = shell_exec("printf '%1.2E' $var");
which could be the cleanest given the script has the permissions to execute commmands.
The E+nn format is the default output format for the linux shell printf.
From the shell:
:~$ echo `printf '%1.2E' 500`
5.00E+02
:~$ echo `printf '%1.2E' 5`
5.00E+00
:~$ echo `printf '%1.2E' 0.05`
5.00E-02

strange behavior of php in implicit convert

strangely the following code return true!
if ('1'==1 && '014'==016)
echo 1;
and output is
1
can anyone tell me why '014' is equal to 016? and how to solve this problem? and if it is possible avoid to do a explicit convert because the data type all the time is vary.
i'm using PHP Version 5.3.8-ZS5.5.0
In PHP, using an integer value with a leading zero leads PHP to assume it's an octal number. Octal 016 is equal to decimal 14.
Using a string such as '014' is implicitly cast to a decimal 14 when used in a comparison with another integer.
See http://php.net/manual/language.types.integer.php
you need to convert string values to integer first, like this:
if(intval('1')==1 && intval('014')==16)
echo 1;
see intval()
Try this one.
<?php
if (ltrim((int)'1',0) == ltrim(1,0) && ltrim((int)'014',0)== ltrim('016', '0'))
echo 1;

Formatting Numbers with PHP [duplicate]

This question already has answers here:
Print numeric values to two decimal places
(6 answers)
Closed 11 months ago.
I'm saving numbers in MySQL using double(10,2).
The numbers are getting saved like:
456.2
232.20
764
On output, I want to force 2 decimals and add the necessary trailing zeros (currency).
Here is the function I'm using and it isn't working.
function format_currency_form($get_money) {
$money_output = abs(number_format($get_money, 2, '.', ''));
return $money_output;
}
(I'm using ABS because I want the value to display as a positive number regardless of its true value in the db)
Here is the code block used to output the data:
<?php echo format_currency_form($row_rs_data['trans_amount']); ?>
No errors getting thrown and no trailing zeros...
Any ideas?
Thanks
Brett
If you are dealing with currency try to use moneyformat
http://php.net/manual/en/function.money-format.php
money_format('%.2n', $number)
In your case the abs should be done in this way:
$number=-11.44;
$money_output = money_format('%.2n', abs($number));
echo $money_output;
If you are dealing with currencies (I think so) money_format gives you a lot of options.
Use sprintf to output formatted strings.
echo sprintf("%.2f", format_currency_form($blah_blah));

Random Number: converting JavaScript to PHP

I have the following line of code in javascript:
(Math.random() + "") * 1000000000000000000
which generates numbers like:
350303159372528000
I tried the same thing in PHP with this:
rand()*1000000000000000000
Which returns:
2.272e+21
I need to use PHP as the number generated will be stored as a SESSION variable and will be used by JavaScript later on.
How do I get PHP to force the number to be an int rather than a float?
EDIT PHP seems to struggle with this.
Would it work if I just generated the rand number in PHP saved it to the SESSION and then done the multiplying by 1000000000000000000 in JavaScript?
How would I go about this?
I'd recommend calling
PHP_INT_MAX
To see if your PHP installation can handle an integar that large. I'm guessing it can't which is why it is knocking it down to scientific notation.
I'd suggest converting your result to an int:
intval(rand()*1000000000000000000)
That said, see Kolink and Jeremy1026 answers for precision issues. If you only need an unique identifier, see Truth's answer.
Update: if you're using strings to represent your numbers, don't want or can't use an arbitrary precision library, and don't stricly need perfecly fair random numbers, you could generate smaller numbers and concat them together:
strval(rand()*999999999 + 1) . strval(rand()*1000000000)
(The +1 is to avoid a leading zero in your result; note also that your number will never have a single digit, but every other number is possible)
For a random number with (exactly) 18 digits, you can also use str_pad in the 2nd part, to fill it with leading zeros:
strval(rand(100000000,999999999)) .
str_pad(strval(rand(0,999999999)), 9, "0", STR_PAD_LEFT)
If you need a unique identifier (which is what it looks like you're trying to do), please use PHP's uniqid() function.
floor() / ceil() / round() / (int) / intval() will convert the number to int.
Also, rand() takes two arguments. If ints are supplied - it will return an integer
And printf() should take care of printing in the format you wish (printf('%d', $int) should do the trick)
In the end I solved the issue like this:
<?php
error_reporting(0);
function RandNumber($e){
for($i=0;$i<$e;$i++){
$rand = $rand . rand(0, 9);
}
return $rand;
}
echo RandNumber(18);
// Outputs a 18 digit random number
?>

Categories