I have 3 numbers returned from a database that I need to add together. For a total of 1,740.01, I get like 10.00. These are floating point numbers. Here are the actual numbers I'm having a problem with.
> 1,729.13
> 10.88
> 0.00
How do I get the correct total of these numbers?
EDIT
$cash = preg_replace('/\$/', '', $cash);
$card = preg_replace('/\$/', '', $card);
$check = preg_replace('/\$/', '', $check);
$cash = number_format(array_sum($cash), 2);
$card = number_format(array_sum($card), 2);
$check = number_format(array_sum($check), 2);
$total = number_format( $cash + $card + $check, 2 );
Don't add values that have been formatted using number_format(), otherwise they may well contain , as a thousand's separator... they're treated as strings rather than floats.
Assuming that $cash, $card and $check are arrays:
$cash = array_sum($cash);
$card = array_sum($card);
$check = array_sum($check);
$total = number_format( $cash + $card + $check, 2 );
$cash = number_format( $cash, 2 );
$card = number_format( $card, 2 );
$check = number_format( $check, 2 );
Do any formatting after the math
EDIT
Use str_replace() rather than preg_replace() to strip out any $, then it's simple addition rather than needing to do the array_sum(), though I'm not sure where any $ is likely to come from if the values are DECIMAL 10,7 from the database
$cash = (float) str_replace( array('$',','), '', $cash );
$card = (float) str_replace( array('$',','), '', $card );
$check = (float) str_replace( array('$',','), '', $check );
$total = number_format( $cash + $card + $check, 2 );
$cash = number_format( $cash, 2 );
$card = number_format( $card, 2 );
$check = number_format( $check, 2 );
(assumes that , is your thousands separator in the string values for $cash, $card and $check when doing the str_replace()
EDIT 2
To convert the $cash array to a sum of its values, having cleaned up any $ or , in the strings:
$cash = array ( 0 => '$1729.13', 1 => '0.00', 2 => '$1,234.56' );
function cleanArrayValues($value) {
return (float) str_replace( array('$',','), '', $value );
}
$cash = array_sum(array_map('cleanArrayValues',$cash));
I've added an extra value into the $cash array just to demonstrate.
You'll need to filter $card and $checks in the same way, using the cleanArrayValues() callback function (if they're all arrays)
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 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'm trying to modify a pseudo-shopping cart (it's array based storing values in user meta and not database) PHP file that wrongly displays currency > 1000 as 0.01
Here's the block I want to change:
public function get_cart_value()
{
$cart = $this->cart;
$prices = array();
$cart = apply_filters('ss_mod_cart_value', $cart);
foreach ($cart['products'] as $product)
{
array_push( $prices, array('price'=>trim($product['price']), 'discount' => trim($product['discount'] )));
}
$total = 0;
foreach($prices as $price)
{
$price = $this->calc_discount($price['price'], $price['discount']);
$price = str_replace('.', '', $price['final_price']);
$total += $price;
}
$total = number_format($total/100, 2);
return $total;
}
The cart button it works on will correctly display the total values of items less than 4 digits, for example:
300 + 500 = 800
but
300 + 500 + 1000 = 800.01 instead of 1,800
I've been trying to change number_format() to make it work but cannot find a solution.
I think by this line
$price = str_replace('.', '', $price['final_price']);
300+500+ "1000";
your numbers like 1,000 are converted to a string and then your total becomes 801.
you have to convert to float in proper way as suggested in this
PHP: unformat money
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
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);