Add a period to the middle string PHP - php

It will actually be a decimal but that is not the main point. I will have a set of numbers like:
8976
8765
3454
3453
10198
What I am wanting to do is add a decimal 2 places from the right. So the first would be 89.76 and so forth.

Can't you just multiply each by 0.01?

$formatted = number_format($unformatted_number / 100, 2, '.', '');
2 - decimal places
'.' - decimal separator
'' - thousands separator
docs for the function are here.

try this
$number = 8976;
$number = (float)$number/100;
results:
89.76
You may have to do some checking to see how many digits the number is, i.e 89768 would be devided by 1000 and so on.

Comments are available,
//the string you need to split
$string = "123456";
// read from right 2 character
$rightNums = substr($string, -2, 2);
// maximum 100 character to the left defined now
$otherNums = substr($string, -4, 100);
// pront them just with . between
echo $otherNums.".".$rightNums; ?>
hope it help much.

Try with this
$tmpString = substr("8976", 0, -2);
$finalString = str_replace($tmpString, "." . $tmpString, "8976");
echo $finalString;

Related

Replacing First 4 digits of a 10 digit number with x

I'm trying to replace the first 4 digits of a number with X, for example:
$num= 1234567890
I want the output to appear like this: XXXX567890
I have tried the function:
$new = substr($num, 0, -4) . 'xxx';
but It only removes the last 4 digits so what should I do ?
You can use the same in opposite
$num= 1234567890;
$new = 'xxxx' . substr($num, 4);
echo $new;
second parameter tells about starting point for string and parity(positive or negative) tells about direction. positive number means to right of string and negative number means to left of string.
http://php.net/manual/en/function.substr.php
With substr_replace function:
$num = 1234567890;
print_r(substr_replace($num, 'XXXX', 0, 4)); // XXXX567890
Another solution is to use str_pad which "fills up" the string to 10 elements with "X".
$num= 1234567890;
Echo str_pad(substr($num,4), 10, "X",STR_PAD_LEFT);
https://3v4l.org/tKtB7
Or if the string lenght is not always 10 use:
Echo str_pad(substr($num,4), strlen($num), "X",STR_PAD_LEFT);
I think this one can be helpful for achieving desired output.
Solution 1:
Try this code snippet here
<?php
ini_set('display_errors', 1);
$num= 1234567890;
echo "XXXX".substr($num, 4);//concatenating 4 X and with the substring
Solution 2: Try this code snippet here
<?php
ini_set('display_errors', 1);
$num= 1234567890;
$totalDigits=4;
echo str_repeat("X", $totalDigits).substr($num, $totalDigits);// here we are using str_repeat to repeat a substring no. of times
Output: XXXX567890
If have written a tiny function to do tasks like this.
function hide_details($str, $num = 4, $replace = 'x') {
return str_repeat($replace, $num).substr($str, $num);
}
echo hide_details('1234567890');

split a number into whole number , decimal points and trailing digits

I have variables of bitcoin values all rounded to 8 decimal places. eg
1.00645600
I need a way in jQuery or php to get the whole number [1], The decimal values [006456], and trailing zeros [00]. I have already tried php substr but it messed up with the results since im dealing with variables.
Simple and general solution in PHP without involving regular expressions (that is an option also):
$number = '1.00645600';
$flooredNumber = floor($number); // 1
$decimalPart = (string) (floatval($number) - $flooredNumber); // 0.006456
$decimals = str_replace('0.', '', $decimalPart); // 006456
$trailingZeros = str_replace(rtrim($number, '0'), '', $number); // 00
substr
Returns the portion of string specified by the start and length parameters.
http://php.net/manual/en/function.substr.php
If the numbers in your string are always in the same position you can use substr() to get the desired values:
$str = '1.00645600';
echo substr($str, 0, 1)."\r\n";
echo substr($str, 2, 2)."\r\n";
echo substr($str, 2, 6)."\r\n";
Output:
1
00
006456
Perhaps, this way?
<?php
$i = '1.00645600';
echo rtrim(rtrim($i, '0'), '.');
?>

Splitting strings through php to query mysql

I need to split a string in two so I can do a SELECT query in my DB. For example, I have the number '0801'. I need to split that number into '08' and '01'. How do I manage to do that?
This is easy to do using the substr() function, which lets you pull out parts of a string. Given your comment that you always have a four-digit number and want it split into two two-digit numbers, you want this:
$input = "0801";
$left = substr($input, 0, 2);
$right = substr($input, 2);
echo "Left is $left and right is $right\n";
According to your comment
The first 2 numbers. It's allways a 4 digit number and I allways need
to split it in 2 two digit numbers
You can simply use
$value = '0801';
$split = str_split($value, 2);
var_dump($split[0]);
var_dump($split[1]);
Just keep in mind $value variable should always be of a string type, not int.
you can use str_split and list
$str = '0801';
list($first,$second) = str_split($str,2);
echo $first;
// 08
echo $second;
// 01
No one gave a MySQL answer yet...
If you're selecting that number..
SELECT
SUBSTR(colname, 0, 2) as firstpart,
SUBSTR(colname, 2, 2) as secondpart
FROM table

Efficient way of removing extraneous zeros from prices?

I have prices stored to five decimal places of precision, such as:
1.95000
2.25000
0.01150
2.10000
2.00000
When displaying prices, I'd like to show the standard $X.XX format if the rest of the digits are just zero, but if there are significant digits then I don't want to cut them out (so I can't simply use number_format()).
As an example, the above prices should display as:
1.95
2.25
0.0115
2.10
2.00
This process has to be done on hundreds of prices per page. What's an efficient way of formatting numbers in this manner?
This uses a regex to match everything before the trailing 0s
$i = "$1.00";
$pattern = '/\$(\d+)\.(\d\d)(0*)/';
$replacement = '\$$1.$2';
print preg_replace($pattern,$replacement,$i);
Another way using rtrim on everything after the first 2 digits right of the decimal
$pos = strpos($i, '.') + 3;
print substr($i, 0, $pos) . rtrim(substr($i, $pos), '0');
This is kind of ugly but it does the job:
function formatPrice($price) {
$out = (float)$price; // Trim off right-hand 0's
$out = "$out"; // Typecast back to string
if ((strlen($out) - strpos($out, '.')) <= 2) { // Test for string length after decimal point
$out = number_format($out, 2); // Format back with 0's
}
return $out;
}
Testing it now... Works!
Here's a one-liner function from my other comment thanks to #FuzzyTree's answer:
function formatPrice($price) {
return substr($price, 0, strpos($price, '.') + 3) . rtrim(substr($price, strpos($price, '.') + 3), '0');
}

Advanced Php Number Formatting

I want to have a PHP number formatted with a minimum of 2 decimal places and a maximum of 8 decimal places. How can you do that properly.
Update: I'm sorry, my question is say I have number "4". I wish for it to display as "4.00" and if I have "2.000000001" then it displays as "2.00" or if I have "3.2102" it will display as such. There is a NSNumber formatter on iPhone, what is the equivalent in PHP.
This formats the $n number for 8 decimals, then removes the trailing zero, max 6 times.
$s = number_format($n, 8);
for($i=0; $i<8-2; $i++) {
if (substr($s, -1) == '0')
$s = substr($s, 0, -1);
}
print "Number = $s";
Use sprintf() to format a number to a certain number of decimal places:
$decimal_places = 4;
$format = "%.${decimal_places}f";
$formatted = sprintf($format,$number);
I don't understand why you would want to display numbers to an inconsistent degree of accuracy. I don't understand what pattern you're trying to describe in your comment, either.
But let us suppose that you want the following behaviour: you want to express the number to 8 decimal places, and if there are more than 2 trailing zeroes in the result, you want to remove the excess zeroes. This is not much more difficult to code than it is to express in English. In pseudocode:
$mystring = string representation of number rounded to 8 decimal places;
while (last character of $mystring is a 0) {
chop off last character of $mystring;
}
Check the number format function:
<?php
$num = 43.43343;
$formatted = number_format(round((float) $num, 2), 2);
?>
http://php.net/manual/en/function.number-format.php
Using preg_match just get the zero ending with and then rtim it
<?php
$nn = number_format(10.10100011411100000,13);
preg_match('/[0]+$/',$nn,$number);
if(count($number)>0){
echo rtrim($nn,$number[0]);
}
Hope it will help you.

Categories