I'm trying to modify a variable from a form.
I want to get rid of any "," but keep the "." while changing it to "%2e"
$price = '6,000.65';
//$price = preg_replace('.', '%2e', $price);
$price = urlencode($price);
echo $price;
This is the exact result from your question:
$price = str_replace(',', '', $price);
$price = str_replace('.', '%2e', $price);
echo $price;
But why would you urlencode it...? If you want to strip unallowed characters (everything but digits and a dot), use the next function:
$price = preg_replace('/[^0-9.]/', '', $price);
// OP requested it...
$price = str_replace('.', '%2e', $price);
echo $price;
Alternatively, you can convert the string into a floating point number and use number_format() to format it nicely.
// note that numbers will be recognised as much as possible, but strings like `1e2`
// will be converted to 100. `1x2` turns into `1` and `x` in `0` You might want
// to apply preg_replace as in the second example
$price = (float)$price;
// convert $price into a string and format it like nnnn.nn
$price = number_format("$price", 2, '.', '');
echo $price;
Third option, works in a similar way. % is a special character for sprintf, marking a conversation specification. .2 tells it to have two decimals and f tells it's a floating point number.
$price = sprintf('%.2f', $price);
echo $price;
// printf combines `echo` and `sprintf`, the below code does the same
// except $price is not modified
printf('%.2f', $price);
References:
http://php.net/str-replace
http://php.net/preg-replace
http://php.net/number-format
http://php.net/sprintf
http://php.net/printf
http://php.net/manual/en/function.str-replace.php
$newPhrase = str_replace($findWhat, $replaceWith, $searchWhere);
so in your case:
$newPrice = str_replace(",", "", $price);
$price = '6,000.65';
$price = str_replace(',','',str_replace('.', '%2e',&$price));
$price = urlencode($price);
Related
I have the number 43.95
I want to convert it to the become 4395.
How do I simply do this in 1 line?
I currently have it like this:
$priceDollars = intval($priceSum);
$priceCents = $priceSum - $priceDollars;
$priceCents = round($priceCents, 2);
$priceCents = substr((string)$priceCents, 2);
print_r("$priceDollars and $priceCents");
$priceDollars=(string)$priceDollars;
$priceCents=(string)$priceCents;
$price = $priceDollars.$priceCents;
$price = (int)$price;
print_r($price);
<?php
$dec = 43.95;
echo $int = (int)str_replace('.', '', (string)$dec);//4395
a) If numbers after decimal will always be 2 then multiply by 100
<?php
$price = 43.95;
echo $price*100;
https://3v4l.org/CN9T4
b) Otherwise, you can use the #Diego De Vita code given in the comments under your question.
intval( str_replace(".", "", $pricesum) );
https://3v4l.org/dUXm2
I have this variable
$option_value['price'] = 2
$option_value['price_prefix'] = +
$this->data['price2'] = 3
I have tried to make sum from it like this
$price = $option_value['price'].''.$option_value['price_prefix'].''.$this->data['price2'];
echo $price
but the result is 2. What I want is 5.
Prease help
Under the assumption that the prefix is always either + or -, something like this should do the trick (I've changed the variable names for the sake of readability):
$price = 2;
$prefix = "+";
$price2 = 3;
$total = $price + ($prefix.$price2);
This concatenates the prefix and the second price to "+3" which will then be cast implicitly to an integer for the addition with the first price. The parentheses make sure that the concatenation is done before the addition. Otherwise the addition would precede and that would lead to concatenation rather than addition.
You can do this like this:
<?php
$option_value['price'] = 2;
$option_value['price_prefix'] = '+';
$option_value['price2'] = 3;
$price = $option_value['price']+$option_value['price_prefix']+$option_value['price2'];
echo $price;
?>
I'm new to php and I'm trying to use number_format :
number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
As in the title, my goal is to modify decimal point and thousands separator without changing the number of decimals as below:
$Num=123456.789;
$Num2=number_format ($Num, [decimals as in $Num], ",", "'" );
My result should be:
$Num2="123'456,789";
Edit
I need a code for an unknown number of decimals
You can use NumberFormatter.
You will still need to specify a certain amount of fraction digits, but you can just use a high enough value and be fine. It's not like the number of digits is really arbitrary. It's tied to your precision ini setting.
$formatter = new NumberFormatter("en_US", NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 42);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "'");
$formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, ",");
echo $formatter->format(123456.7891234); // 123'456,7891234
Demo https://3v4l.org/TCAIA
You can do it such a way (firstly take a look to #Gordon answer – it's much more better):
<?php
function extendedNumberFormat($num, $decimalSeparator, $thousandSeparator) {
$asStr = strval($num);
$exploded = explode('.', $asStr);
$int = $exploded[0];
$decimal = isset($exploded[1]) ? $exploded[1] : null;
$result = number_format($int, 0, ".", $thousandSeparator);
if ($decimal !== null) {
$result .= $decimalSeparator . $decimal;
}
return $result;
}
echo extendedNumberFormat(123456.789, ',', "'") . "\n";
echo extendedNumberFormat(123456.7891, ',', "'") . "\n";
echo extendedNumberFormat(123456, ',', "'") . "\n";
//123'456,789
//123'456,7891
//123'456
I am using PHP number_format to express prices of products, using decimal point, thousands separators, etc. For example:
$price = 20.456;
print "$" . number_format($price, 2, ".", ",");
outputs $20.46.
However, I would like that, if the price is integer, for example $price = 20.00, to output $20. Is there some other function or rule to achieve this, avoiding decimal points if not necessary?
Just do a loose comparison of $price cast as integer against $price, if they match (ie. it's a whole number), you can format to 0 decimal places:
number_format($price, ((int) $price == $price ? 0 : 2), '.', ',');
You can use ternary operator fot that:
$price = 20.456;
print "$" . ($price == intval($price) ? number_format($price, 0, "", ",") : number_format($price, 2, "", ","));
Try $price = 20.456 +0 ;
$price + 0 does the trick.
echo 125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7
Internally, this is equivalent to casting to float with (float)$price or floatval( $price) but I find it simpler.
A little helper function my_format to determine if the number is an integer and then return the corresponding string.
function my_format($number)
{
if (fmod($number, 1) == 0) {
return sprintf("$%d\n", $number);
} else {
return sprintf("$%.2f\n", $number);
}
}
$price = 20.456;
echo my_format($price);
echo my_format(20);
Will output
$20.46 $20
A little solution that works for any number
$price = "20.5498";
$dec = fmod($price, 1);
if($dec > 0)
print "$" . number_format($price, 2, ".", ",");
else
print "$" . floor($price);;
You can use floor() function
$price = 20.456;
echo '$'.floor($price); // output $20
I have this
$example = "1234567"
$subtotal = number_format($example, 2, '.', '');
the return of $subtotal is "1234567.00"
how to modify the definition of $subtotal, make it like this "1,234,567.00"
Below will output 1,234,567.00
$example = "1234567";
$subtotal = number_format($example, 2, '.', ',');
echo $subtotal;
Syntax
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
But I advise you to use money_format which will formats a number as a currency string
You have many options, but money_format can do the trick for you.
// Example:
$amount = '100000';
setlocale(LC_MONETARY, 'en_IN');
$amount = money_format('%!i', $amount);
echo $amount;
// Output:
"1,00,000.00"
Please note that money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so it is undefined in Windows.
Final edit: Here's a pure PHP Implementation that will work on any system:
$amount = '10000034000';
$amount = moneyFormatIndia( $amount );
echo number_format($amount, 2, '.', '');
function moneyFormatIndia($num){
$explrestunits = "" ;
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
// creates each of the 2's group and adds a comma to the end
if($i==0){
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
}else{
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash; // writes the final format where $currency is the currency symbol.
}
Ref: http://php.net/manual/en/function.money-format.php
string money_format ( string $format , float $number )
ex:
// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56
Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.
Note: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.
Use number_format : http://www.php.net/manual/en/function.number-format.php
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
$number = 123457;
$format_number = number_format($number, 2, '.', ',');
// 1,234.57