Make number format? - php

Make format of number:
For example:
if number = 204433
output = 204K
if number = 84243
output = 84'243
if number = 8000
output = 8000
if number = 400
output = 400
How to formatted number to that's format?

The number_format command can do what you are looking for.
string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
You wrote:
if number = 84243
output = 84'243
Example:
$in = 84243;
$out = number_format ( $in, 0, ".", "'");
// $out = "84'243"

I think you can try this
if(strlen($number) > 5) {
echo substr($number,0,2).'K';
} elseif(strlen($number)) {
echo numberformat($number,2,'.',"'"); // for example
} else {
echo $number;
}

Related

If value is empty or 0,0 echo something else in php

i code a value for my progress bar in percent. But i need a if / else for the case, when supply is "null" and 0,0. Doesn't work so far. Maybe someone can help me out.. what is wrong here. I appreciate it.
case 'supplyper':
$x = $coin->available_supply;
$y = $coin->total_supply;
$percent = $x/$y;
$percent_friendly = number_format( $percent * 100, 0 ) . '%'; // change 2 to # of decimals
if (empty($y)) {
$text = '0';
}
// Evaluates as true because $var is set
if (isset($y)) {
$text = '' . $percent_friendly . '';
}
As it seems that $coin->total_supply is a string, first you need to make sure that it can be turn into a valid numeric value. It seems you are using the character ',' as your decimal separator so wee need to replace it with the '.' in order to make it a valid float. So lets try this:
$y = str_replace(',', '.', $coin->total_supply);
Now we need to make sure $y is a valid float representation:
$y = floatval($y);
Now check for $y not being zero(0) before you calculate the percentage otherwise you are open to a division by zero error.
You are very close, try this:
$x = str_replace(',', '.', $coin->available_supply);
$x = floatval($x);
$y = str_replace(',', '.', $coin->total_supply);
$y = floatval($y);
if (empty($y)) {
$text = '100%';
} else {
$percent = $x/$y;
$percent_friendly = number_format( $percent * 100, 0 ) . '%'; // change 2 to # of decimals
$text = '' . $percent_friendly . '';
}

Hide numbers of a phone number

How can I show and hide the some numbers of a phone number by replacing it with * like 0935***3256 by PHP?
EX:
09350943256 -> 0935***3256 09119822432 -> 0911***2432
09215421597 -> 0921***1597...
$number = '09350943256';
echo str_pad(substr($number, -4), strlen($number), '*', STR_PAD_LEFT);
Top php code result is as: *******3256 but i want result as: 0935***3256
How is it?
You could use substr and concat this way
to work for any $number with any number of n digit length
<?php
$number = "112222";
$middle_string ="";
$length = strlen($number);
if( $length < 3 ){
echo $length == 1 ? "*" : "*". substr($number, - 1);
}
else{
$part_size = floor( $length / 3 ) ;
$middle_part_size = $length - ( $part_size * 2 );
for( $i=0; $i < $middle_part_size ; $i ++ ){
$middle_string .= "*";
}
echo substr($number, 0, $part_size ) . $middle_string . substr($number, - $part_size );
}
The output if you make $number = "1" is * and if $number = "12" is *2 and for $number = "112222" is 11**22. and it goes on.
In short:
$phone = 01133597084;
$maskedPhone = substr($phone, 0, 4) . "****" . substr($phone, 7, 4);
// Output: 0113****7084
You can use substr_replace() function
<?php
$mobnum ="09350943256";
for($i=4;$i<7;$i++)
{
$mobnum = substr_replace($mobnum,"*",$i,1);
}
echo $mobnum;
?>
You can use substr() to fetch the first 4 and last 4, and add four * in the middle manually, and put it all together in a string.
$phone = "09350943256";
$result = substr($phone, 0, 4);
$result .= "****";
$result .= substr($phone, 7, 4);
echo $result;
The above would output
0935****3256
Live demo
<?php
$phone='05325225990';
function stars($phone)
{
$times=strlen(trim(substr($phone,4,5)));
$star='';
for ($i=0; $i <$times ; $i++) {
$star.='*';
}
return $star;
}
$result=str_replace(substr($phone, 4,5), stars($phone), $phone);
echo $result;
?>
0532*****90
Instead of doing the math of calculating indices, I suggest this „declarative“ solution:
<?php
$number='0123456789';
$matches=[];
preg_match('/(\\d{4})(\\d+)(\\d{4})/', $number, $matches);
$result=$matches[1].str_repeat('*',strlen($matches[2])).$matches[2];
print($result);
?>

Convert array result into integer for calculating

I have a little problem with an array.
I have an array which looks like this:
Array
(
[start] => Array
(
[0] => 15168
)
[ende] => Array
(
[0] => 43
)
[string] => Array
(
[0] => 1050
)
)
The number I need is 1050. So I get it like this:
$number = $tabelle['string'][0];
Now my problem is that I can't use it in calculations. I already tried to convert it into an integer with the following line:
$number = intval($tabelle['string'][0]);
But this doesn't work. I always get 0 for $number. How to do it properly? I already searched on Google for about 2 hours.
Best regards
My whole script:
<?php
class data_pars {
var $datei;
var $read_laenge = 2000;
var $result;
function set_datei($datei) {
$this->datei = $datei;
}
function read($start,$ende) {
$file = #fopen ($this->datei,"r");
while (!feof($file)) {
$inhalt .= fgets($file,$this->read_laenge);
}
if(!$start) $start = 0;
if(!$ende) $ende = strlen($inhalt);
if($ende > strlen($inhalt)) $ende = strlen($inhalt);
$this->result = substr($inhalt,$start,$ende);
}
function get_result() {
return $this->result;
}
function get_in_out($in,$out,$in_out) {
$anzahl_ende = strlen($out);
$anzahl_start = strlen($in);
$start = 0;
$anzahl = substr_count($this->result, $in);
$count = 0;
if(!$in_out) {
$ad_start = $anzahl_start;
$ad_ende = $anzahl_ende;
}
while($count < $anzahl) {
$ar_start = strpos($this->result, $in, $start);
$ar_ende = strpos($this->result, $out, $ar_start + $anzahl_start);
$ar_string = substr($this->result,$ar_start + $ad_start, $ar_ende - $ar_start + $anzahl_ende - $ad_ende - $ad_start);
$output[start][] = $ar_start;
$output[ende][] = $ar_ende - $ar_start + $anzahl_ende;
$output[string][] = trim($ar_string);
$start = $ar_start + $anzahl_start;
$count++;
}
return $output;
}
}
$data = new data_pars();
$data->set_datei('http://www.elitepvpers.com/theblackmarket/profile/6005376');
$data->read('0','20000');
$tabelle = $data->get_in_out('<td>elite*gold:</td>','</td>',false);
$number = intval($tabelle['string'][0]);
echo '<pre>';
print_r($tabelle);
echo '</pre>';
echo $number;
?>
So I always get 0 for $number instead of 1050;
You did 2 main errors:
1. You have to initialize $inhalt before your while loop like this:
$inhalt = "";
while (!feof($file)) {
$inhalt .= fgets($file,$this->read_laenge);
}
2. You forgot to put quotes around the indexes:
$output["start"][] = $ar_start;
$output["ende"][] = $ar_ende - $ar_start + $anzahl_ende;
$output["string"][] = trim($ar_string);
And now why did your intval() failed? Because if you right click and show source you will see in the array the value is:
<td>1050
So this can't convert to a int! And the <td> you don't see, because it's a html tag
Now you can easy extract only the number with this lines:
$tabelle["string"]["0"] = filter_var($tabelle["string"]["0"], FILTER_SANITIZE_NUMBER_INT);
echo $number = intval($tabelle["string"]["0"]);
Output:
1050
If I understand your code and logic correctly.
try replace:
$output[start][] = $ar_start;
$output[ende][] = $ar_ende - $ar_start + $anzahl_ende;
$output[string][] = trim($ar_string);
to this:
$
output['start'][] = intval($ar_start);
$output['ende'][] =intval( $ar_ende - $ar_start + $anzahl_ende);
$output['string'][] = intval(trim($ar_string));

round number in php

Hello how do I round the following to two decimal places .
echo
"<div class='quote-results-result'>ex VAT £" .
((($_POST['qtylitres'] * $price ['Price']) + $fuelmargin['margin']) / 1.2) .
"</div>"
I need to round the price bit of a php novice.
Use number_format function like this:
$number = 1234.56789
$new_number = number_format($number, 2, '.', '');
echo $new_number;
Output: 1234.57
round($VARIABLE_NAME,2); //This rounds off the variable to 2 decimal places
Use round function from php manuals
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
function roundoff($number,$format)
{
if($number != '') {
$newNumber=$this->exp_to_dec($number);
$num = explode('.',$newNumber);
//pr($num);
if(isset($num[1]) && $num[1] != 0) {
$dec = substr($num[1],0,$format);
} else {
$dec = '00';
}
} else {
$num[0] = 0;
$dec = '00';
}
return $num[0].'.'.$dec;
}
function exp_to_dec($float_str)
// formats a floating point number string in decimal notation, supports signed floats, also supports non-standard formatting e.g. 0.2e+2 for 20
{
// make sure its a standard php float string (i.e. change 0.2e+2 to 20)
// php will automatically format floats decimally if they are within a certain range
$float_str = ( string ) (( float ) ($float_str));
// if there is an E in the float string
if (($pos = strpos ( strtolower ( $float_str ), 'e' )) !== false) {
// get either side of the E, e.g. 1.6E+6 => exp E+6, num 1.6
$exp = substr ( $float_str, $pos + 1 );
$num = substr ( $float_str, 0, $pos );
// strip off num sign, if there is one, and leave it off if its + (not required)
if ((($num_sign = $num [0]) === '+') || ($num_sign === '-'))
$num = substr ( $num, 1 );
else
$num_sign = '';
if ($num_sign === '+')
$num_sign = '';
// strip off exponential sign ('+' or '-' as in 'E+6') if there is one, otherwise throw error, e.g. E+6 => '+'
if ((($exp_sign = $exp [0]) === '+') || ($exp_sign === '-'))
$exp = substr ( $exp, 1 );
else
trigger_error ( "Could not convert exponential notation to decimal notation: invalid float string '$float_str'", E_USER_ERROR );
// get the number of decimal places to the right of the decimal point (or 0 if there is no dec point), e.g., 1.6 => 1
$right_dec_places = (($dec_pos = strpos ( $num, '.' )) === false) ? 0 : strlen ( substr ( $num, $dec_pos + 1 ) );
// get the number of decimal places to the left of the decimal point (or the length of the entire num if there is no dec point), e.g. 1.6 => 1
$left_dec_places = ($dec_pos === false) ? strlen ( $num ) : strlen ( substr ( $num, 0, $dec_pos ) );
// work out number of zeros from exp, exp sign and dec places, e.g. exp 6, exp sign +, dec places 1 => num zeros 5
if ($exp_sign === '+')
$num_zeros = $exp - $right_dec_places;
else
$num_zeros = $exp - $left_dec_places;
// build a string with $num_zeros zeros, e.g. '0' 5 times => '00000'
$zeros = str_pad ( '', $num_zeros, '0' );
// strip decimal from num, e.g. 1.6 => 16
if ($dec_pos !== false)
$num = str_replace ( '.', '', $num );
// if positive exponent, return like 1600000
if ($exp_sign === '+')
return $num_sign . $num . $zeros;
// if negative exponent, return like 0.0000016
else
return $num_sign . '0.' . $zeros . $num;
} // otherwise, assume already in decimal notation and return
else
return $float_str;
}

Function to add dashes to US phone number in PHP

What is the best way to add dashes to a phone number in PHP? I have a number in the format xxxxxxxxxx and I want it to be in the format xxx-xxx-xxxx. This only applies to 10 digit US phone numbers.
$number = "1234567890";
$formatted_number = preg_replace("/^(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $number);
EDIT: To be a bit more generic and normalize a US phone number given in any of a variety of formats (which should be common practice - there's no reason to force people to type in a phone number in a specific format, since all you're interested in are the digits and you can simply discard the rest):
function localize_us_number($phone) {
$numbers_only = preg_replace("/[^\d]/", "", $phone);
return preg_replace("/^1?(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $numbers_only);
}
echo localize_us_number("5551234567"), "\n";
echo localize_us_number("15551234567"), "\n";
echo localize_us_number("+15551234567"), "\n";
echo localize_us_number("(555) 123-4567"), "\n";
echo localize_us_number("+1 (555) 123-4567"), "\n";
echo localize_us_number("Phone: 555 1234567 or something"), "\n";
$number = '1234567890';
if(ctype_digit($number) && strlen($number) == 10) {
$number = substr($number, 0, 3) .'-'.
substr($number, 3, 3) .'-'.
substr($number, 6);
}
Or if you for some reason want to avoid substr:
$number = '1234567890';
if(ctype_digit($number) && strlen($number) == 10) {
$parts = str_split($number, 3);
$number = $parts[0] .'-'. $parts[1] .'-'. $parts[3].$parts[4];
}
iterate through the string and make counter. When counter is 3 or 7 insert dash.
I feel obliged to post. Cheesiest solution:
$number = "1234567890";
$formatted_number = "$number[0]$number[1]$number[2]-$number[3]$number[4]$number[5]-$number[6]$number[7]$number[8]$number[9]";
But it works and its fast. vs. the preg_replace solution:
250,000 iterations:
preg_replace: 1.23 seconds
ugly solution: 0.866 seconds
Pretty meaningless but fun :P
Here's what I used. It's not perfect, but it's an improvement over #Thilo's answer. It checks for a leading 1. If it's there, it ignores it. The code also ignores separating dashes, commas, and spaces, so it will work with 1231231234, 123 123 1234, and 123.123.1234. It doesn't handle numbers with parenthesis, but I'm sure there's another thread out there with that solution!
$formatted_number = preg_replace("/^1?(?:[- .])?(\d{3})(?:[- .])?(\d{3})(?:[- .])?(\d{4})$/", "($1) $2-$3", $not_formatted_phone_number);
A modification of Thilo's answer providing complete conditional formatting control over the leading "1".
public function phoneFormat($number) {
$numbersOnly = preg_replace("/[^\d]/", "", $number);
$nums = array_filter(explode("-", preg_replace("/^(1|)(\d{3})(\d{3})(\d{4})$/",
"$1-$2-$3-$4", $numbersOnly)));
$output = $numbersOnly;
if(count($nums) == 3){
$output = "($nums[1])-$nums[2]-$nums[3]";
}elseif(count($nums) == 4){
$output = "$nums[0]-($nums[1])-$nums[2]-$nums[3]";
}
return $output;
}
Here's what I came up with:
function format_phone($var_num) {
$var_num = trim($var_num);
$var_num = str_replace("(","",$var_num);
$var_num = str_replace(")","",$var_num);
$var_num = str_replace("-","",$var_num);
$var_num = str_replace(" ","",$var_num);
$var_num = str_replace(".","",$var_num);
$var_num = substr($var_num, -10);
$var_area_code = substr($var_num, 0, -7);
$var_exchange = substr($var_num, 3, -4);
$var_extention = substr($var_num, -4);
$var_return = "{$var_area_code}-{$var_exchange}-{$var_extention}";
return $var_return;
}
// Examples:
$phone_number = "1 (757) 555-1212";
// $phone_number = "17575551212";
// $phone_number = "(757) 555-1212";
// $phone_number = "757.555.1212";
echo "{$phone_number} = " . format_phone($phone_number);

Categories