I have to do arithmetic with some ternary (base 3) numbers. I know I can use base_convert to get from a ternary string ("2001022210") to an integer. Is there an existing function to do the inverse?
I want "some_function" such that:
$someInteger = base_convert("2001022210", 10, 3);
some_function($someInteger);
answers "2001022210". I'm happy to provide extra arguments ...
some_function($someInteger, 3);
some_function($someInteger, 3, 10);
I know I can code this myself, but I'm hoping it's already there.
$someInteger is now in base 3... so just do $base10Int = base_convert($someInteger, 3, 10); to get it back.
Tom. Please head over to http://php.net/ when you use php functions to see what they actually do. Reading and understanding a languages API is a general key for writing good code.
string base_convert ( string $number , int $frombase , int $tobase )
Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase have to be between 2 and 36, inclusive. Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35.
Now let $number be the number you want to convert:
If you want to convert it from ternary to decimal you use base_convert($number, 3, 10);
If you want to convert it from decimal to ternary you use base_convert($number, 10, 3);
Yes, this can be done with base_convert():
As the PHP Manual says:
base_convert — Convert a number between arbitrary bases
So, the following would work:
base_convert($someinteger, 3, 10);
As a function:
function some_func($someinteger) {
return base_convert($someinteger, 3, 10);
}
Related
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.
I need to display a floating point number with a specified number of decimal places (rounding up), specifically up to two decimal places even though the number has no fractional part. One way that I know is by using the sprintf() PHP function as follows.
echo sprintf("%0.2f", 123);
It returns 123.00.
echo sprintf("%0.2f", 123.4555);
returns 123.46 but the following doesn't return what I need.
echo sprintf("%0.2f", 123.455); // 5 is removed - the right-most digit.
I expect it to return 123.46 but it doesn't. It returns 123.45. Although it's not a huge difference, I somehow need to return 123.46 in both of the cases.
The round() function can do it. echo round(123.455, 2); and echo round(123.4555, 2); return 123.46 in both the cases but I can't think of using this function because if the fractional part is not present, it displays no decimal digits at all. like echo round(123, 2); gives 123 and I need 123.00.
Is there a function in PHP to achieve this?
number_format(123.455, 2, '.', '')
I have a project where I have to generate random numbers from 00000 till 99999.
The randomizing isn't where I get stuck, but the fact that it always needs 5 characters is. So when it generates the number 14, I want it as 00014.
What is the best way to achieve this?
sprintf() can do that:
echo sprintf('%05d', 0);
Or use str_pad() - but that's a little bit longer in code:
echo str_pad(0, 5, 0, STR_PAD_LEFT);
str_pad() is able to do what you need the code to be done.
Simply:
$s = str_pad('14', 5, '0', STR_PAD_LEFT);
generate integers with leading 0's
An integer will never have leading 0's.
If you need leading 0's you nedd to convert the integer to an string -> see the answer from thephpdeveloper. This is the right way for writing an number with leading 0's into a database - for example.
If you like to work with that integer (for example for calculations) it's better to leave the integer as an integer (don't change to string) and every time you need to output those numbers -> take the solution from "Stefan Gehrig"
Even substr() can do it:
print substr('0000' . $myRandomNumber, -5);
(Not that I would recommend this. Just wanted to contribute :) )
my script calculates a number X by dividing two other numbers, A by B.
X=A/B
when i use number_format(A,2) on A before calculating X, i get a very odd number. Actual figures:
1,045.00 / 5 = 0.2
but if i don't use number_format on A before the division, i get the correct answer. Is number_format somehow making A into a non-number?
1045 / 5 = 209
number_format should be used only while pretty printing the number. Its return value should not used in calculation as you did.
Example:
If $A = 1045;
then number_format($A,2) will be 1,045.00 now if you treat 1,045.00 as a number it will be 1 as comma and remaining char will be ignored and 1/2 is 0.5 which you are getting.
You want round(A, 2), not number_format() which is for string representations (hence named "format").
The docs show that number_format returns a string. Have you tried casting the result of number_format() to a numeric type before your mathematical manipulation?
I had similar issues. It could be better if we use number format dec_point and thousand_separator parameters. you could use number_format($number, 2, '.', ''); It will help to remove your thousand separator
number_format makes it into a string with commas between thousands, and the comma will be confusing the divisor into thinking that's the decimels based on your locale.
I need a random 4 digit number
right now im using rand(1000,9999) that always gives me a 4 digit number but i eliminates 0000-0999 as possible results.
how do you pad a random number?
(also this is eventually going to be added to a string do i need to cast the int as a string?)
thanks
In scripting languages like PHP, you don't have to cast in 99% of the cases.
Padding could be done using
sprintf("%04u", rand(0, 9999));
Explanations
the first argument of sprintf specifies the format
% stays for the second, third, forth etc. argument. the first % gets replaced by the second argument, the second % by the third etc.
0 stays for the behaviour of filling with 0 to the left.
4 stays for "At least 4 characters should be printed"
u stays for unsigned integer.
sprintf("%04d", rand(0,9999))
should do what you want
Quick and dirty... how about doing:
rand(10000,19999)
and take the last four digits:
substr(rand(10000, 19999), 1, 4)
str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
Use mt_rand() instead of rand(), it's better.
You can use str_pad() or sprintf() to format your string:
$rand = rand(0, 9999);
$str1 = str_pad($rand, 4, '0', STR_PAD_LEFT);
$str2 = sprintf('%04u', $rand);