I have the following numbers:
000000006375 and I want to output 63.75
000000004500 and I want to output just 45
Basically, if the last two numbers are not zero, I wanted to make it a float value wherein a decimal point will be added. But if the last 2 numbers are zeros I just want to output a whole number which in the example is just 45.
I was thinking of casting the numbers to int first but I do not know how to convert it to a float number if there last 2 digits are non-zeros.
You can use this code:
$s = '000000006375';
$i = (int) $s /100; // 63.75
echo "000000006375" / 100;
echo '<br />';
echo "000000004500" / 100;
// Output: 63.75<br />45
For your use case you might just cast it into an integer and divide with 100, like this:
$t1 = "000000006375";
$t2 = "000000004500";
var_dump(myfunc($t1), myfunc($t2));
function myfunc($in) {
$out = (int) $in / 100;
return $out;
}
The output will be something like...
float(63.75)
int(45)
print round('000000006375'/100,2);
print '<br/>';
print round('000000004500'/100,2);
$int = (int)'000000004500';
echo round((substr($int, 0, -2) . '.' . substr($int, -2)),2);
This is one way to do it :)
Related
#if($user->dettagli->facebook_follower >= 1000 && $user->dettagli->facebook_follower <= 999999)
<?php
echo(round($user->dettagli->facebook_follower, 5,PHP_ROUND_HALF_DOWN) . "K");
?>
{{$user->dettagli->facebook_follower / 1000}} K
#endif
Hi could someone please help me. I am using Laravel and trying to display a users Facebook follower count, but I got a little stuck with something. I am taking their int at for example 1589 followers and trying to return in the blade "1.5k". On screen I return either 1589k with this php call or 1.589k. How do I get that number to one decimal place and become only 1.5k??
thank you!
As per the docs
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
You are specifying a precision of 5. You should change this to 1.
Change your function call to:
echo(round($user->dettagli->facebook_follower, 1, PHP_ROUND_HALF_DOWN) . "K");
EDIT: I mis-read the question. This is a function that should handle numbers into the millions.
You would need to use laravel-twigbridge to make the function available in your templates though.
function pretty_number(int $n): string {
$prettyN = $n;
$suffix = '';
$len = strlen((string) $n);
$suffixes = ['K', 'M'];
foreach ($suffixes as $s) {
if ($n < 1000) {
break;
}
$suffix = $s;
$n = $n / 1000;
$prettyN = number_format($n, 1);
}
return $prettyN . $suffix;
}
echo pretty_number(100); // 100
echo pretty_number(999); // 99
echo pretty_number(1589); // 1.6K
echo pretty_number(1600); // 1.6K
echo pretty_number(1589300); // 1.6M
You can use the NumberFormatter. This can be defined in a global place so you only need to use the third line in your blade view.
$a = new \NumberFormatter("en-US", \NumberFormatter::DECIMAL);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 1);
echo $a->format($user->dettagli->facebook_follower);
I need to echo number(variable) in two ways and i need help with code for this equation.
Example:
Variable is 5003
First echo has to be: 5000 (rounded)
Second echo has to be just the rounded digits: 3
So i want to know if and how can i achieve this equation, im thinking among lines of: variable(5003) minus rounded variable(5000) equals 3
So that way if variable is lets say 15009
Fist will be 15000
Second will be 9
I hope this make sense, thank you for help
You should look into the roundPHP function:
You can have negative decimal points like this:
round(5003, -3); // returns 5000
round(15009, -3); // returns 15000
To figure out the difference you can do like this:
$input = 5003
$x = $input;
$y = round($input, -3);
$z = $x - $y; // z is now 3
PHP is not a mathematical language, so it cannot solve equations for you.
You can make a more general solution like this:
$inputs = [
5003,
15009,
55108,
102010
];
foreach ($inputs as $input) {
$decimals = floor(log10($input)) - 1;
$rounded = round($input, -1 * $decimals);
echo "$input - $rounded = " . ($input - $rounded) . PHP_EOL;
}
Outputs:
5003 - 5000 = 3
15009 - 15000 = 9
55108 - 55000 = 108
102010 - 100000 = 2010
Assuming that you want to round the last three digits:
$input = 5003;
$rounded = (int)(5003 / 1000) * 1000;
$rest = $input - $rounded;
echo($rounded . "\n" . $rest);
This results in:
5000
3
I am generating some data of latitude and longitude with rand(10000000, 3000000); for example. But I need to calculate distance between two locations, so basically I need to convert my result, for example 22049256 to 22.049256 in order to pass to my function.
How can I achieve this most effectively with using least amount of resources?
TL;DR
I have integer 22049256, needs to be converted to float 22.049256.
Divide by 1M?
22049256 / 1000000 = 22.049256
$foo = rand(10000000, 30000000);
$foo /= 1000000;
echo $foo;
If you always want the decimal after the first two digits, that should do the trick.
<?php
$n = rand(10000000, 3000000);
$len = strlen($n);
$div = pow(10, $len - 2);
$n /= $div;
var_dump($n);
?>
http://codepad.viper-7.com/Nrql15
Basically just dividing by a number made by checking how many characters there are in your original number.
Simplest way would be to treat the number as a string and iterate through it, adding the decimal point at the appropriate position.
$new_number = '';
for($i=0;$i<strlen((string)$number;$i++)
{
if($i == 2)
$new_number .= '.';
$new_number .= substr((string)$number, $i, 1);
}
Edit:
Another possibility is to divide by 1000000 and run number_format to ensure proper decimal places:
$new_number = number_format($number/1000000, 6);
I have system in PHP in which I have to insert a Number which has to like
PO_ACC_00001,PO_ACC_00002,PO_ACC_00003.PO_ACC_00004 and so on
this will be inserted in Database for further reference also "PO and ACC" are dynamic prefix they could different as per requirement
Now my main concern is how can is increment the series 00001 and mantain the 5 digit series in the number?
>> $a = "PO_ACC_00001";
>> echo ++$a;
'PO_ACC_00002'
You can get the number from the string with a simple regex, then you have a simple integer.
After incrementing the number, you can easily format it with something like
$cucc=sprintf('PO_ACC_%05d', $number);
Create a helper function and a bit or error checking.
/**
* Takes in parameter of format PO_ACC_XXXXX (where XXXXX is a 5
* digit integer) and increment it by one
* #param string $po
* #return string
*/
function increment($po)
{
if (strlen($po) != 12 || substr($po, 0, 7) != 'PO_ACC_')
return 'Incorrect format error: ' . $po;
$num = substr($po, -5);
// strip leading zero
$num = ltrim($num,'0');
if (!is_numeric($num))
return 'Incorrect format error. Last 5 digits need to be an integer: ' . $po;
return ++$po;
}
echo increment('PO_ACC_00999');
Sprintf is very useful in situations like this, so I'd recommend reading more about it in the documentation.
<?php
$num_of_ids = 10000; //Number of "ids" to generate.
$i = 0; //Loop counter.
$n = 0; //"id" number piece.
$l = "PO_ACC_"; //"id" letter piece.
while ($i <= $num_of_ids) {
$id = $l . sprintf("%05d", $n); //Create "id". Sprintf pads the number to make it 4 digits.
echo $id . "<br>"; //Print out the id.
$i++; $n++; //Letters can be incremented the same as numbers.
}
?>
This question already has answers here:
Zero-pad digits in string
(5 answers)
Closed 2 years ago.
I have a variable which contains the value 1234567.
I would like it to contain exactly 8 digits, i.e. 01234567.
Is there a PHP function for that?
Use sprintf :
sprintf('%08d', 1234567);
Alternatively you can also use str_pad:
str_pad($value, 8, '0', STR_PAD_LEFT);
Given that the value is in $value:
To echo it:
printf("%08d", $value);
To get it:
$formatted_value = sprintf("%08d", $value);
That should do the trick
When I need 01 instead of 1, the following worked for me:
$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
sprintf is what you need.
EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
Though I'm not really sure what you want to do you are probably looking for sprintf.
This would be:
$value = sprintf( '%08d', 1234567 );
Simple answer
$p = 1234567;
$p = sprintf("%08d",$p);
I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.
To clip the first 8 digits
$p = substr(sprintf('%08d', $p),0,8);
To clip the last 8 digits
$p = substr(sprintf('%08d', $p),-8,8);
If the input numbers have always 7 or 8 digits, you can also use
$str = ($input < 10000000) ? 0 . $input : $input;
I ran some tests and get that this would be up to double as fast as str_pad or sprintf.
If the input can have any length, then you could also use
$str = substr('00000000' . $input, -8);
This is not as fast as the other one, but should also be a little bit faster than str_pad and sprintf.
Btw: My test also said that sprintf is a little faster than str_pad. I made all tests with PHP 5.6.
Edit: Altough the substr version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234' will only result in the last 3 digits
$no_of_digit = 10;
$number = 123;
$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
$number = '0'.$number;
}
echo $number; /////// result 0000000123
I wrote this simple function to produce this format: 01:00:03
Seconds are always shown (even if zero).
Minutes are shown if greater than zero or if hours or days are required.
Hours are shown if greater than zero or if days are required.
Days are shown if greater than zero.
function formatSeconds($secs) {
$result = '';
$seconds = intval($secs) % 60;
$minutes = (intval($secs) / 60) % 60;
$hours = (intval($secs) / 3600) % 24;
$days = intval(intval($secs) / (3600*24));
if ($days > 0) {
$result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
}
if(($hours > 0) || ($result!="")) {
$result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
}
if (($minutes > 0) || ($result!="")) {
$result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
}
//seconds aways shown
$result .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $result;
} //funct
Examples:
echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.