Trim zeros from decimal part php - php

My exact requirement is, if the second decimal of the value is zero,
the value should only have one decimal. For others, it should have two decimal.
eg 1. 150.00 to 150.0
eg 2. 150.10 to 150.1
eg 3. 150.76 to 150.76
What I need to know is whether there is any PHP function to do this.
echo floatval("150.00")."<br>";
echo floatval("150.10")."<br>";
echo floatval("150.76")."<br>";
The result is as follows:
150
150.1
150.76
I need to have 150.0 instead of 150. I just need to know if there is any php function. Otherwise I will be able to write code.

You can use substr() function also to remove last char if it is 0. May be the below code will help you
function roundit($string)
{
$string = number_format($string,2);
if (substr($string, -1, 1) == '0')
{
$string = substr($string, 0, -1);
echo $string;
}
else
echo $string;
}
roundit('150.00');
roundit('150.10');
roundit('150.76');

You may write a simple function to help you out with that. Something like this could do the trick:
<?php
function removeTrailingZero($num){
$num = floatval($num);
$pieces = explode(".", $num);
for($i=0; $i<count($pieces); $i++){
if(isset($pieces[1])){
$pieces[1] = preg_replace("#0*$#", "", $pieces[1]);
break;
}else{
$pieces[1] = '0';
break;
}
}
return rtrim(implode(".", $pieces), ".");
//return floatval(rtrim(implode(".", $pieces), "."));
}
var_dump(removeTrailingZero(123.45));
var_dump(removeTrailingZero(67.80));
var_dump(removeTrailingZero(90));
var_dump(removeTrailingZero(100.00000));
// PRODUCES:::
string '123.45' (length=6)
string '67.8' (length=4)
string '90.0' (length=4)
string '100.0' (length=5)

Related

Using preg_replace() To Increment a Digit in a Phrase [duplicate]

I have a string formed up by numbers and sometimes by letters.
Example AF-1234 or 345ww.
I have to get the numeric part and increment it by one.
how can I do that? maybe with regex?
You can use preg_replace_callback as:
function inc($matches) {
return ++$matches[1];
}
$input = preg_replace_callback("|(\d+)|", "inc", $input);
Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.
Ideone link
Alternatively this can be done using preg_replace() with the e modifier as:
$input = preg_replace("|(\d+)|e", "$1+1", $input);
Ideone link
If the string ends with numeric characters it is this simple...
$str = 'AF-1234';
echo $str++; //AF-1235
That works the same way with '345ww' though the result may not be what you expect.
$str = '345ww';
echo $str++; //345wx
#tampe125
This example is probably the best method for your needs if incrementing string that end with numbers.
$str = 'XXX-342';
echo $str++; //XXX-343
Here is an example that worked for me by doing a pre increment on the value
$admNo = HF0001;
$newAdmNo = ++$admNo;
The above code will output HF0002
If you are dealing with strings that have multiple number parts then it's not so easy to solve with regex, since you might have numbers overflowing from one numeric part to another.
For example if you have a number INV00-10-99 which should increment to INV00-11-00.
I ended up with the following:
for ($i = strlen($string) - 1; $i >= 0; $i--) {
if (is_numeric($string[$i])) {
$most_significant_number = $i;
if ($string[$i] < 9) {
$string[$i] = $string[$i] + 1;
break;
}
// The number was a 9, set it to zero and continue.
$string[$i] = 0;
}
}
// If the most significant number was set to a zero it has overflowed so we
// need to prefix it with a '1'.
if ($string[$most_significant_number] === '0') {
$string = substr_replace($string, '1', $most_significant_number, 0);
}
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.
>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'
This is similar to the answer above, but contains the code inline and does a full check for the last character.
function replace_title($title) {
$pattern = '/(\d+)(?!.*\d)+/';
return preg_replace_callback($pattern, function($m) { return ++$m[0]; }, $title);
}
echo replace_title('test 123'); // test 124
echo replace_title('test 12 3'); // test 12 4
echo replace_title('test 123 - 2'); // test 123 - 3
echo replace_title('test 123 - 3 - 5'); // test 123 - 3 - 6
echo replace_title('123test'); // 124test

adding an increment to a variable [duplicate]

I have a string formed up by numbers and sometimes by letters.
Example AF-1234 or 345ww.
I have to get the numeric part and increment it by one.
how can I do that? maybe with regex?
You can use preg_replace_callback as:
function inc($matches) {
return ++$matches[1];
}
$input = preg_replace_callback("|(\d+)|", "inc", $input);
Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.
Ideone link
Alternatively this can be done using preg_replace() with the e modifier as:
$input = preg_replace("|(\d+)|e", "$1+1", $input);
Ideone link
If the string ends with numeric characters it is this simple...
$str = 'AF-1234';
echo $str++; //AF-1235
That works the same way with '345ww' though the result may not be what you expect.
$str = '345ww';
echo $str++; //345wx
#tampe125
This example is probably the best method for your needs if incrementing string that end with numbers.
$str = 'XXX-342';
echo $str++; //XXX-343
Here is an example that worked for me by doing a pre increment on the value
$admNo = HF0001;
$newAdmNo = ++$admNo;
The above code will output HF0002
If you are dealing with strings that have multiple number parts then it's not so easy to solve with regex, since you might have numbers overflowing from one numeric part to another.
For example if you have a number INV00-10-99 which should increment to INV00-11-00.
I ended up with the following:
for ($i = strlen($string) - 1; $i >= 0; $i--) {
if (is_numeric($string[$i])) {
$most_significant_number = $i;
if ($string[$i] < 9) {
$string[$i] = $string[$i] + 1;
break;
}
// The number was a 9, set it to zero and continue.
$string[$i] = 0;
}
}
// If the most significant number was set to a zero it has overflowed so we
// need to prefix it with a '1'.
if ($string[$most_significant_number] === '0') {
$string = substr_replace($string, '1', $most_significant_number, 0);
}
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.
>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'
This is similar to the answer above, but contains the code inline and does a full check for the last character.
function replace_title($title) {
$pattern = '/(\d+)(?!.*\d)+/';
return preg_replace_callback($pattern, function($m) { return ++$m[0]; }, $title);
}
echo replace_title('test 123'); // test 124
echo replace_title('test 12 3'); // test 12 4
echo replace_title('test 123 - 2'); // test 123 - 3
echo replace_title('test 123 - 3 - 5'); // test 123 - 3 - 6
echo replace_title('123test'); // 124test

Replacing random numbers in a php string serial numbers(123...)

In PHP, how to convert a string containing mixture of random letters and numbers to a string containing serial numbers along with random numbers without changing their position in a string? For example,
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
Now, I want to convert this string into
$str_b = "1)Apple 2)Ball 3)Cat 4)Dog 5)Egg";
I want the numbers 1,5,3,8,4 to be 1,2,3,4,5.
This should work for you:
Just use preg_replace_callback() and replace each digit (\d+ => 0-9 as many times as possible) with an incrementing number, .e.g
<?php
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
$start = 1;
echo $newStr = preg_replace_callback("/\d+/", function($m)use(&$start){
return $start++;
}, $str_a);
?>
output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg
Created Simple looping program:
$str_a = "1)Apple 5)Ball 3)Cat 8)Dog 4)Egg";
function change($str_a) {
$counter = 1;
for($i=0; $i<strlen($str_a); $i++) {
if(is_numeric($str_a[$i])) {
$str_a[$i] = $counter++;
}
}
return $str_a;
}
print(change($str_a))
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg
You can use preg_split and then concatenate it incrementing by 1. This will work also for numbers consisting of multiple digits:
$str_a = "51)Apple 675)Ball 334)Cat 84)Dog 904)Egg";
$a = preg_split('/\b\d+/', $str_a);
$str_b = '';
for($i=0,$c = count($a);$i<$c;$i++){
if($i){
$str_b .= $i.$a[$i];
}
}
echo $str_b;
Output:
1)Apple 2)Ball 3)Cat 4)Dog 5)Egg

Adding a string and an integer in php

I'm trying to add a 1 in front of my binary code and this is how I'm going about it:
if I have 0101, for example, then I'd add a number with 4 zeroes, like 10000 so it would become 10101. Here's my code:
$fill = strlen($string);
$number = '1';
$add = str_pad($number, $fill, '0', STR_PAD_RIGHT);
$m1 = $string + $add;
The problem is the output for that is something like 1.random number e+Random number
assuming $string is your "0101" string, you could just do $m1 = '1'.$string;
My previous answer was wrong because the length of the string is potentially variable and str_pad requires you to know the length. This will work, but it doesn't look so elegant:
if (strpos($string, '0') === 0) {
$string = '1' . $string;
}

Replacing last x amount of numbers

I have a PHP variable that looks a bit like this:
$id = "01922312";
I need to replace the last two or three numbers with another character. How can I go about doing this?
EDIT Sorry for the confusion, basically I have the variable above, and after I'm done processing it I'd like for it to look something like this:
$new = "01922xxx";
Try this:
$new = substr($id, 0, -3) . 'xxx';
Result:
01922xxx
You can use substr_replace to replace a substring.
$id = substr_replace($id, 'xxx', -3);
Reference:
http://php.net/substr-replace
function replaceCharsInNumber($num, $chars) {
return substr((string) $num, 0, -strlen($chars)) . $chars;
}
Usage:
$number = 5069695;
echo replaceCharsInNumber($number, 'xxx'); //5069xxx
See it in action here: http://codepad.org/XGyVQ1hk
Strings can be treated as arrays, with the characters being the keys:
$id = 1922312; // PHP converts 01922312 => 1 because of that leading zero. Either make it a string or remove the zero.
$id_str = strval($id);
for ($i = 0; $i < count($id_str); $i++)
{
print($id_str[$i]);
}
This should output your original number. Now to do stuff with it, treat it as a normal array:
$id_str[count($id_str) - 1] = 'x';
$id_str[count($id_str) - 2] = 'y';
$id_str[count($id_str) - 3] = 'z';
Hope this helps!
Just convert to string and replace...
$stringId = $id . '';
$stringId = substr($id, 0, -2) . 'XX';
We can replace specific characters in a string using preg_replace(). In my case, I want to replace 30 with 50 (keep the first two digits xx30), in the $start_time which is '1030'.
Solution:
$start_time = '1030';
$pattern = '/(?<=\d\d)30/';
$start_time = preg_replace($pattern, '50', $start_time);
//result: 1050

Categories