I'm trying to split a line of PHP up, the reason being I don't actually always need some of the code and so that I can reuse parts of it.
The main reason I'm doing this is because the currency I get shows more digits for some currencies e.g. 1.2562 instead of 1.25, so I want to use the substr function only on certain GET's and be able to modify it for other GET's.
http://prntscr.com/6ttw8o
symbol is always required, substr isn't, $converter always required, end part of substr isn't however it can change, new currency is required.
$symbol[2] . substr(($converter->convert($defaultCurrency, $newCurrency) * 1), 0, 4) . " <b>" .$newCurrency. "</b>";
I've tried doing this with explode, however I'm not entirely sure how to do it as I have never really had to split anything up before so I'm a little puzzled on how to go about it.
Once the code has gone through the GET checking which is the current one set, I want it to grab the specified split up code pieces and then output it.
Put your code in a function like this:
function formatCurrency($symbol, $converter, $defaultCurrency, $newCurrency, $factor=1.0, $suffix="", $substrChars=0) {
if($substrChars>0) {
return $symbol . substr(($converter->convert($defaultCurrency, $newCurrency) * $factor), 0, $substrChars) . $suffix . " <b>" . $newCurrency. "</b>";
} else {
return $symbol . ($converter->convert($defaultCurrency, $newCurrency) * $factor) . $suffix . " <b>" . $newCurrency. "</b>";
}
}
If you call it without the $substrChars parameter, it will omit the substr() call, otherwise it will strip all but the first $substrChars characters:
if( $_GET['currency'] === "GBP" ){
$newCurrency = $_GET['currency'];
$string = formatCurrency($symbol[1], $converter, $defaultCurrency, $newCurrency, 2.0, ".00", 0);
} elseif( $_GET['currency'] === "USD" ){
$newCurrency = $_GET['currency'];
$string = formatCurrency($symbol[2], $converter, $defaultCurrency, $newCurrency, 1.0, "", 4);
}
This solution is very readable because you immediately see the difference between the two branches in the conditional statement.
Related
I'm building an personal app where I can follow my cryptocurrency coins which I'm currently holding and following. The problem I've noticed are the decimals behind the price. A currency normally has max 2 decimals, but the API of Coinmarketcap gives me more depending on how much the price is.
Below is an example of the value I get from the API, and how I actually want the price to be shown. Values above 1000 will get a comma and no decimals.
$950194.0 -> $950,194
$81851.6 -> $81,852
$4364.97 -> $4,365
$326.024 -> $326.02
$35.0208 -> $35.02
$4.50548 -> $4.51
$0.0547128 -> $0.0547128
I've never tried something ever like this before, so I really don't know how to start. Tried using round() and numberFormat(), but couldn't make the same like how I wanted above in the example.
You can use money_format to make thing easier. However, the problem is about what precision do you want. You have to figure it out yourself since I cannot find the pattern from your examples. Yet I wrote the simple function for you with round and money_format. What the rest is adjust the precision to the point where you want in each case.
<?php
function my_money_format($number, $precision=0)
{
$number = preg_replace( '/[^0-9.,]/', '', $number); // clean the input
$number = round($number, $precision);
$format = '%.' . $precision . 'n';
setlocale(LC_MONETARY, 'en_US'); // set money format to US to use $
return money_format($format, $number);
}
echo my_money_format('$950194.0', 0); // $950,194
echo "\n";
echo my_money_format('$81851.6', 0); // $81,852
echo "\n";
echo my_money_format('$4364.97', 0); // $4,365
echo "\n";
echo my_money_format('$326.024', 2); // $326.02
echo "\n";
echo my_money_format('$35.0208', 2); // $35.02
echo "\n";
echo my_money_format('$4.50548', 2); // $4.51
echo "\n";
echo my_money_format('$0.0547128', 7); // $0.0547128
echo "\n";
I'm working on something in zen cart and I don't want .00 to display on prices.
I thought I fixed the issue by doing
$price=number_format($special_price,2,'.','');
but zen cart has a function that adds the required currency symbol to the front or back of the number
$currencies->format($price)
The problem is that this function adds the .00 back onto the value!
The code for the function is
$format_string = $this->currencies[$currency_type]['symbol_left'] . number_format(zen_round($number * $rate, $this->currencies[$currency_type]['decimal_places']), $this->currencies[$currency_type]['decimal_places'], $this->currencies[$currency_type]['decimal_point'], $this->currencies[$currency_type]['thousands_point']) . $this->currencies[$currency_type]['symbol_right'];
If I duplicate that function so that I have $currencies->format2($price) and change it to
$format_string = $this->currencies[$currency_type]['symbol_left'] . number_format(zen_round($number * $rate, $this->currencies[$currency_type]['decimal_places']), $this->currencies[$currency_type]['0'], $this->currencies[$currency_type]['decimal_point'], $this->currencies[$currency_type]['thousands_point']) . $this->currencies[$currency_type]['symbol_right'];
then it will add the currency symbol without adding the decimal places back in. Of course, when you have a price such as 49.50 it is then rounding this up to 50
I did try
$cur_price=$currencies->format($special_price);
$price=str_replace(".00", "", (string)number_format ($cur_price, 2, ".", ""));
The thinking behind it being that I could apply the currencies symbol first and then remove the decimals if they were .00, but that resulted in a blank space where the price should be.
I either need to find a way to check if
$price
ends in .00 so i can conditionally call $currencies->format() or $currencies->format2(), or I need to modify the original function to not put the decimal in place if it's .00, but allow it at all other times.
Would
$price = substr($price, -3) == ".00" ? substr($price, 0, -3) : $price;
work?
You can use PHP's explode() function to split the price into two parts (the part before and after the decimal), then check to see if it's what you want.
Try running the code below, then run it again after changing the $curr_price to something ending in 00.
<?php
$curr_price = '45.99';
$price_array = explode('.', $curr_price);
if ($price_array[1] == '00')
{
$curr_price = $price_array[0];
}
echo 'The price is ' . $curr_price . "<br>";
?>
Building a php calculator application and I'm a little confused on how I would do a specific case.
In general, I'm checking the input via a regular expression using preg_match but
what I'm confused about is how to cover the case of 09+0, I want to make sure that no number has a zero and then a number to the right of it.
On the left, it can be anything other than / sign. Some more examples include the following : 01+100, 33+011 etc (essentially, I want to let the user know this is bad input but having a difficult time figuring what the best way to check for it would be.
Edit 1 (Code so far) :
$input=$_GET["expr"];
$nospace_input=str_replace(' ', '', $input);
$input = str_replace('--','+',$input);
$correct_format=preg_match("/^[-.,0-9][-+*.\/, 0-9]+$/",$input);
if ($correct_format==0 && $nospace_input=="") {
//do nothing
}
elseif ($divby_zero==1) {
echo "Can't do div by zero!";
}
elseif($correct_format==1) {
$result = eval('return ' .$input. ';');
echo $input . " = " . $result;
}
else {
echo "Not valid";
}
Regardless of what format the input is in, I am trying to use PHP to modify it, so the output is always consistent, rounds to two decimal places and has a dollar sign. My approach does not yield desired results all the time, I was wondering if someone can help me come up with a more robust solution?
Desired output:
$num = "$12.00"; //output $12.00
$num = "125"; //output $125.00
$num = "$300"; //output $300.00
$num = "17.5"; //output $17.50
$num = "1,777.5"; //output $1777.50
What I tried, however this does not work for all cases:
$num = "$" . str_replace("$", "", round($num,0)) . ".00";
I appreciate any advice! Many thanks in advance!
$num = "$" . str_replace("$", "", round($num,0));
In this line you round before you remove the $-sign. I must be the other way round:
$num = "$" . round(str_replace("$", "", $num),0);
EDIT: And to get the output you want, you might want to use number_format() instead of round()
$num = "$" . number_format(str_replace("$", "", $num),2, '.', '');
I have a problem, it'll probably become apparent as you read my function, but I can't figure out what to do.
The issue is, I need to use "do, while", because I need the result of "do", to test in "while". The problem is, when the while gets all 4 conditions returning false, it quits, but that leaves me with a bad code.
I need to regenerate a code until it contains no indistinguishable characters.
function make_code(){
do{
$prefix = mt_rand(0, mt_getrandmax());
$code = uniqid($prefix);//good to make sure we always have a unique string to work with, even with no seed supplied.
$sha1 = sha1($code);
$base_convert = base_convert($sha1, 16, 36);//expand hex with the rest of the alphabet.
$substr = substr($base_convert, 0, 12);//we only want the first 12 characters.
$strtoupper = strtoupper($substr);//for aesthetics.
$str_split = str_split($strtoupper, 4);//seperate into chunks.
$voucher_code = $str_split[0] . self::CS . $str_split[1] . self::CS . $str_split[2];//build
}
while(
(stristr($voucher_code, "o") === false)
&& (stristr($voucher_code, "0") === false)
&& (stristr($voucher_code, "1") === false)
&& (stristr($voucher_code, "i") === false));
return $voucher_code;
}
}
Thanks for any help offered.
Wouldn't it be easier to just present this code in a font that DOES make those characters distinguishable? That being said, simply use a regex to "simplify" your multiple string matches:
do {
...
while (preg_match('/[01lo]/i', $voucher_code));
Eliminating those characters from usage just makes it that much more likely you'll end up with a duplicate voucher.