I need a function to check if number have 2 decimals or not.
For example:
$number = '1.00'; // Valid
$number2 = '1'; // Not valid
$number3 = '1.000' //Not valid
You can check it like that:
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
You would have to convert your variable to a String, but this is not a big problem. Do it like that:
$d = 100.0/81.0;
$s = strval($d);
You can do something like this:
if(strlen(substr(strrchr($number, "."), 1)) == 2){
echo "valid";
}else{
echo "not valid";
}
Regex could be a solution since your numbers seem to be declared as strings.
Code :
<?php
$re = "/(\d\.\d{2})(?!\d)/";
$array_input = array('1.00', '1', '1.000');
foreach($array_input as $row)
{
if(preg_match($re, $row, $matches) == 0)
echo $row . " isn't a valid value with 2 decimals only. <br>";
else
echo $row . " is valid. <br>";
}
?>
Output :
1.00 is valid.
1 isn't a valid value with 2 decimals only.
1.000 isn't a valid value with 2 decimals only.
Why would you not just force them to have 2 decimals using something like this
$original = 2;
$float = number_format($number, 2);
// echo $float = 2.00
I guess if you need to enforce that a float only has 2 decimals you could do something like the following.
$numbers = array(2.453, 3.35, 2.53, 1.636);
foreach($numbers as $number) {
if(strpos($number, '.') !== false) {
if(strlen($parts[1]) == 2) {
echo $number .' is valid!';
} else {
echo $number .' is NOT valid!';
}
}
}
The above is one way to accomplish this but there are many others. You could use array_map or array_filter and you could also use math such as the following
$numbers = array(2.453, 3.35, 2.53, 1.636);
$valid_numbers = array_filter($numbers, function($number) { return strlen($number) - strpos($number, '.');
function check_decimals($input, $number_of_decimals)
{
if(strlen(substr(strrchr((string)$input, "."), 1)) == $number_of_decimals)
{
return TRUE;
}
else {
return FALSE;
}
}
check_decimals("1.000", 2);
This may be a solution using preg_match_all
$re = "/^\\d+(?:\\.\\d{2})?$/m";
$str = "1.00\n13333.55\n1.000";
preg_match_all($re, $str, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
REGEX: https://regex101.com/r/nB7eC4/1
CODE: http://codepad.viper-7.com/49ZuEa
Related
I'm not so familiar with php, but i know we could find the place value of a given number through php. For example if the input is 23.56 it should echo 2 - Tens, 3 - Ones, 5 - Hundredths, 6 - Thousandths.
Any idea would be appreciated. :) please help.
Try
$str = '23.56';
$strdiv = explode('.', $str);
$before = array('Tens', 'Ones');
$after = array('Hundredths', 'Thousandths');
$counter = 0;
foreach($strdiv as $v) {
for($i=0; $i<strlen($v); $i++) {
if(!empty($v)) {
if($counter == 0) {
$newarr[] = substr($v,$i, 1).' - '.$before[$i];
}
if($counter == 1) {
$newarr[] = substr($v,$i, 1).' - '.$after[$i];
}
}
}
$counter++;
}
echo implode(', ',$newarr); //2 - Tens, 3 - Ones, 5 - Hundredths, 6 - Thousandths
<?php
$mystring = '123.64';
$findme = '.';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of '.' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Another method:
$num = 23.56;
$arr = array("Tens","Ones","Hundredths","Thousandths");
$num = str_replace(".","",$num);
for ($i=0;$i<strlen($num);$i++) {
$res[] = $num[$i] ." - ".$arr[$i];
}
echo implode(', ',$res);
Answer for all writers:
1) Dont use for in php! Dont use! Use foreach but dont use for! Why? php stored all array keys as STRING its very slow!
$arr = array('a', 'b', 'c');
var_dump($arr[0] === $arr['0']); // true
2) Your solutions in three lines:
function humanityFloat($v) {
$out = str_split(str_replace('.', '', sprintf('%01.2f', (float) $v)));
array_walk($out, function(&$a, $i, $s) { $a .= ' - ' . $s[$i]; }, array('Tens', 'Ones', 'Hundredths', 'Thousandths'));
return join(', ', $out);
}
echo humanityFloat(22) . PHP_EOL;
Of course this function not check input parameters - this example. But example return valid result for all unsigned float or decimal numbers between 10 and 99.99
I want to remove last digit from decimal number in PHP.
Lets say I have 14.153. I want it to be 14.15. I will do this step till my number is no longer decimal.
I think this should work:
<?php
$num = 14.153;
$strnum = (string)$num;
$parts = explode('.', $num);
// $parts[0] = 14;
// $parts[1] = 153;
$decimalPoints = strlen($parts[1]);
// $decimalPoints = 3
if($decimalPoints > 0)
{
for($i=0 ; $i<=$decimalPoints ; $i++)
{
// substring($strnum, 0, 0); causes an empty result so we want to avoid it
if($i > 0)
{
echo substr($strnum, 0, '-'.$i).'<br>';
}
else
{
echo $strnum.'<br>';
}
}
}
?>
echo round(14.153, 2); // 14.15
The round second parameter sets the number of digits.
You can try this.
Live DEMO
<?php
$number = 14.153;
echo number_format($number,2);
I had problem with php I just dont get it,
here is my code
$pieces = explode("|", $result);
if (count($pieces) == 3){
$size = $pieces[2];
echo "here";
if($bw>=$pieces[2]){
$manfi = $bw - $pieces[2];
echo "<br>$manfi<br>";
echo $size;
}
else{
echo "is not big!!!";echo $size."aaa". $bw;
}
and here is the out put
hereis not big!!!183773480 aaa 1000000000000000
i just cant figure it out , how this number 1000000000000000 is less than 183773480 ?
The problem is that the number 1000000000000000 is of the datatype string. If you then compare it to an integer it will be casted to an integer. Since 1000000000000000 overflows a 32bit integer that PHP uses it will become a negative value.
try:
$bw = intval($bw);
$pieces = array_map(intval, explode("|", $result));
if (count($pieces) == 3){
$size = $pieces[2];
echo "here";
if($bw>=$pieces[2]){
$manfi = $bw - $pieces[2];
echo "<br>$manfi<br>";
echo $size;
}else{
echo "is not big!!!";echo $size."aaa". $bw;
}
}
I changed $pieces so that it contains an array of integers and I also made sure that $bw contains an integer
function restyle_text($input){
$input = number_format($input);
$input_count = substr_count($input, ',');
if($input_count != '0'){
if($input_count == '1'){
return substr($input, +4).'k';
} else if($input_count == '2'){
return substr($input, +8).'mil';
} else if($input_count == '3'){
return substr($input, +12).'bil';
} else {
return;
}
} else {
return $input;
}
}
This is the code I have, I thought it was working. apparently not.. can someone help since I can't figure this out.
Try this:
http://codepad.viper-7.com/jfa3uK
function restyle_text($input){
$input = number_format($input);
$input_count = substr_count($input, ',');
if($input_count != '0'){
if($input_count == '1'){
return substr($input, 0, -4).'k';
} else if($input_count == '2'){
return substr($input, 0, -8).'mil';
} else if($input_count == '3'){
return substr($input, 0, -12).'bil';
} else {
return;
}
} else {
return $input;
}
}
Basically, I think you're using the substr() wrong.
Here's a generic way to do this that doesn't require you to use number_format or do string parsing:
function formatWithSuffix($input)
{
$suffixes = array('', 'k', 'm', 'g', 't');
$suffixIndex = 0;
while(abs($input) >= 1000 && $suffixIndex < sizeof($suffixes))
{
$suffixIndex++;
$input /= 1000;
}
return (
$input > 0
// precision of 3 decimal places
? floor($input * 1000) / 1000
: ceil($input * 1000) / 1000
)
. $suffixes[$suffixIndex];
}
And here's a demo showing it working correctly for several cases.
I re-wrote the function to use the properties of numbers rather than playing with strings.
That should be faster.
Let me know if I missed any of your requirements:
function restyle_text($input){
$k = pow(10,3);
$mil = pow(10,6);
$bil = pow(10,9);
if ($input >= $bil)
return (int) ($input / $bil).'bil';
else if ($input >= $mil)
return (int) ($input / $mil).'mil';
else if ($input >= $k)
return (int) ($input / $k).'k';
else
return (int) $input;
}
I do not want to spoil the moment... but I think this is a little more simplified.
Just improving #Indranil answer
e.g.
function comp_numb($input){
$input = number_format($input);
$input_count = substr_count($input, ',');
$arr = array(1=>'K','M','B','T');
if(isset($arr[(int)$input_count]))
return substr($input,0,(-1*$input_count)*4).$arr[(int)$input_count];
else return $input;
}
echo comp_numb(1000);
echo '<br />';
echo comp_numb(1000000);
echo '<br />';
echo comp_numb(1000000000);
echo '<br />';
echo comp_numb(1000000000000);
Or you can too use library How it works is here
Juste install composer require stillat/numeral.php and
<?php
require_once __DIR__.'/vendor/autoload.php';
$formatter = new Stillat\Numeral\Numeral;
$formatter->setLanguageManager(new Stillat\Numeral\Languages\LanguageManager);
$formatter->format(1532, '0a,0'); //Affiche 1.5K
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);