php - add comma thousands separator but remove trailing zeros - php

I am trying to use PHP to format a number to
Remove all trailing zeros
Add a comma for the thousands separator
List two decimal points, assuming that they are not zeros
I tried this, but its not doing exactly what I am trying to achieve:
$prices[$title]['reg_price'] = (float)number_format($membership->sell_price, 2, ".", "");
$prices[$title]['three_year_price'] = (float)number_format($membership->attributes[$aid]->options[$three_year_oid]->price, 2, ".", "");
I had found that I could strip trailing zeros by casting the number to a float. However, I found that I needed to tell number_format NOT to use the thousands comma separator, because otherwise, when casting 1,500.00 to a float, the result was 1.
So, in summary, I want my code to change 1500.00 to 1,500, 150.00 to 150, and 19.99 to 19.99. How can I make this happen?

function parseCurrency($value) {
if ( intval($value) == $value ) {
$return = number_format($value, 0, ".", ",");
}
else {
$return = number_format($value, 2, ".", ",");
/*
If you don't want to remove trailing zeros from decimals,
eg. 19.90 to become: 19.9, remove the next line
*/
$return = rtrim($return, 0);
}
return $return;
}
$prices[] = parseCurrency(1500.00);
$prices[] = parseCurrency(1500.10);
$prices[] = parseCurrency(1500.1);
$prices[] = parseCurrency(1500);
$prices[] = parseCurrency(123.53);
$prices[] = parseCurrency(1224323.53);
$prices[] = parseCurrency(19.99);
print_r($prices);
Outputs:
Array
(
[0] => 1,500
[1] => 1,500.1
[2] => 1,500.1
[3] => 1,500
[4] => 123.53
[5] => 1,224,323.53
[6] => 19.99
)

This inserts commas, rounds to 2 decimal places, removes trailing zeroes, and removes trailing '.':
rtrim(rtrim(number_format($value,2),0),'.')

You can use the
ltrim($var, '0');
to remove the leading 0. And
rtrim($var, '0');
to remove the trailing.

For replacing "." to "," u can use a function :
function replace_dot($value) {
$str = str_replace('.', ',', $value);
return $str;
}

Related

Trying to fix SKU numbers from 55A_3 to A55_3 with PHP in SQL

I have SKU numbers imported from a CSV file into SQL DB.
Pattern look like:
55A_3
345W_1+04B_1
128T_2+167T_2+113T_8+115T_8
I am trying to move all the letters in front of the numbers.
like:
A55_3
W345_1+B04_1
T128_2+T167_2+T113_8+T115_8
My best idea how to do it was to search for 345W and so, and to replace it with W345 and so:
$sku = "345W_1+04B_1";
$B_range_num = range(0,400);
$B_range_let = range("A","Z");
then generating the find and replace arrays
$B_find =
$B_replace =
maybe just using str_replace??
$res = str_replace($B_find,$B_replace,$sku);
Result should be for all SKU numbers
W345_1+B04_1
Any ideas?
You can use preg_replace to do this job, looking for some digits, followed by a letters and one of an _ with digits, a + or end of string, and then swapping the order of the digits and letters:
$skus = array('55A_3',
'345W_1+04B_1',
'128T_2+167T_2+113T_8+115T_8',
'55A');
foreach ($skus as &$sku) {
$sku = preg_replace('/(\d+)([A-Z]+)(?=_\d+|\+|$)/', '$2$1', $sku);
}
print_r($skus);
Output:
Array
(
[0] => A55_3
[1] => W345_1+B04_1
[2] => T128_2+T167_2+T113_8+T115_8
[3] => A55
)
Demo on 3v4l.org
Here I defined a method with specific format with unlimited length.
$str = '128T_2+167T_2+113T_8+115T_8';
echo convertProductSku($str);
function convertProductSku($str) {
$arr = [];
$parts = explode('+', $str);
foreach ($parts as $part) {
list($first, $second) = array_pad(explode('_', $part), 2, null);
$letter = substr($first, -1);
$number = substr($first, 0, -1);
$arr[] = $letter . $number . ($second ? '_' . $second : '');
}
return implode('+', $arr);
}

Substr not allowing double digit codes to process on form

I have an array that uses two codes in a list and pushes them into a form on the next page. Currently I have:
$code= array();
$code['c1'] = substr($part, 0, 1);
$code['c2'] = substr($part, 2);
Now, If I select anything with a single digit c1 and single or double c2 then it adds to the form.
Examples:
1-9
1-15
9-12
9-9
But if I try to add anything with double digits in c1 it doesn't add, like:
10-1
10-2
10-11
If I try
$codes= array();
$codes['c1'] = substr($part, 0, 2);
$codes['c2'] = substr($part, 2);
Then no codes show up.
How can I account for both?
UPDATE:
Currently, the above code, if I select 10-58, will dump c1 as 1 and c2 as -5
You can easily use explode() and list() to split any combination of codes...
$part = "1-15";
$codes = array();
list($codes['c1'], $codes['c2']) = explode("-", $part);
print_r($codes);
gives...
Array
(
[c1] => 1
[c2] => 15
)
For
$part = "10-15";
it gives...
Array
(
[c1] => 10
[c2] => 15
)
If you are unsure if your data is always correct, you can check that the data has 2 components after using explode() and only convert it then, you can also do something to report and error or whatever you need...
$split = explode("-", $part);
if ( count($split) == 2 ){
$codes['c1'] = $split[0];
$codes['c2'] = $split[1];
}
else {
// Not of correct format.
}
print_r($codes);

Find most common character in PHP String

I am looking for the most efficient way to find the most common character in a php string.
I have a string that looks like this:
"aaaaabcaab"
The result should be stored in the variable $total.
So in this case $total should be equal to a
You can use this function,
function getHighest($str){
$str = str_replace(' ', '', $str);//Trims all the spaces in the string
$arr = str_split(count_chars($str.trim($str), 3));
$hStr = "";
$occ = 0;
foreach ($arr as $value) {
$oc = substr_count ($str, $value);
if($occ < $oc){
$hStr = $value;
$occ = $oc;
}
}
return $hStr;
}
Te easiest way to achieve this is:
// split the string per character and count the number of occurrences
$totals = array_count_values( str_split( 'fcaaaaabcaab' ) );
// sort the totals so that the most frequent letter is first
arsort( $totals );
// show which letter occurred the most frequently
echo array_keys( $totals )[0];
// output
a
One thing to consider is what happens in the event of a tie:
// split the string per character and count the number of occurrences
$totals = array_count_values( str_split( 'paabb' ) );
// sort the totals so that the most frequent letter is first
arsort( $totals );
// show all letters and their frequency
print_r( $totals );
// output
Array
(
[b] => 2
[a] => 2
[p] => 1
)

add delimiters to a phone number

I need to turn this phone number:
5555555555
into this string with delimiters:
"555.555.5555"
Here's my code:
$phone = 5555555555;
$phoneArray = explode(2, $phone);
print_r($phoneArray);
and it returns this:
Array ( [0] => 555 [1] => [2] => 55555 )
What am I doing wrong?
Lots of ways to do this, and RegEx not required, but here's a nice and easy one w/ RegEx:
$phone = '5555555555';
echo preg_replace('/(\d{3})(\d{3})(\d{4})/', "$1.$2.$3", $phone);
Cheers
You need something more like this:
$number = '123456789';
$segments = array();
$segments[] = substr($number, 0, 3);
$segments[] = substr($number, 3, 3);
$segments[] = substr($number, 6, 4);
$number = implode('.', $segments); // Comes out to 123.456.7890
Note that you'll want to do some format checking first. You'll need to verify
that they actually entered a 10-digit number with no dividing symbols.
You probably don't want to use explode since you don't have a known delimiter within the string to cause the split. You could use str_split($phone,3) which would give you 3 array elements of 3, and a 4th of 1. Keep the first two and merge the final two together into your 3rd array elemnent:
$phone = 5555555555;
$phoneArray = str_split($phone,3);
$phoneArray[2] .= phoneArray[3];
print_r($phoneArray);
Hope that helps.

Most efficient way to delimit key

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow.
Use str_split():
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
The output:
Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
Then of course to insert hyphens between the sets you just implode() them together:
echo implode('-', $sets); // echoes '0123-4567-8901-2345'
If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:
preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');
If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.
This is a bit more general:
<?php
// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
$n = func_num_args();
$str = func_get_arg(0);
$ret = array();
if ($n >= 2) {
for($i=1, $offs=0; $i<$n; ++$i) {
$chars = abs( func_get_arg($i) );
$ret[] = substr($str, $offs, $chars);
$offs += $chars;
}
}
return $ret;
}
echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );
?>

Categories