How to do calculation of two values with commas? - php

I have two value and I want to do calculation of those values.
For example :
$a = '750,000.00';
$b = '763,000.00';
echo $a + $b;
and I am getting the result 1513 which is wrong.. The output must be 1513000.
How to do such calculations?

You have to eliminate the commas before the strings are interpreted as float values:
$a = '750,000.00';
$b = '763,000.00';
echo str_replace(',', '', $a) + str_replace(',', '', $b);

Use str_replace:
// replaces all , with nothing
echo str_replace(',','',$a) + str_replace(',','',$b);

The following converts a String to Int:
<?php
$a = (int)'750,000.00';
$b = (int)'763,000.00';
echo $a + $b;
?>
Or String to Float as mentioned by Flinsch
<?php
$a = (float)'750,000.00';
$b = (float)'763,000.00';
echo $a + $b;
?>
However, you may want to take localisation into account (different writing of numbers in different parts of the world).
My Belgian localisation settings outcome this as "1.513" instead of 1.513.000

Related

PHP: convert string to float (only if string represents a float)

I have an unknwon string that could resemble a float. In that case I want to convert it to float (for calculations), otherwise leave it as a string.
How do I detect if a string represents a float number?
$a = "1.23"; // convert $a to 1.23
$b = "1.2 to 1.3"; // leave $b as is
Automatic string conversion would convert the latter to 1.2, but that's not what I want.
You can use is_numeric() function to check variable which might contain a number.
For example:
$a = "1.23";
if (is_numeric($a)) {
$a = (float)$a;
}
$b = "1.2 to 1.3";
if (is_numeric($b)) {
$b = (float)$b;
}
var_dump([
'a' => $a,
'b' => $b
]);
Output
array (size=2) 'a' => float 1.23 'b' => string '1.2 to 1.3'
(length=10)
You can use the following to check if a string is a float:
$a = "1.23";
$isFloat = ($a == (string)(float)$a);
function StrToFloat($var){
if(is_numeric($var)){
return (float)$var;
} else return $var;
}
$a = "1.23"; // convert $a to 1.23
$b = "1.2 to 1.3"; // leave $b as is
$a = StrToFloat($a); // $a = 1.23
$b = StrToFloat($b); // $b = "1.2 to 1.3"
Because it hasn't been mentioned
if(preg_match('/^\d+\.\d+$/', $string)){
$float = (float)$string;
}
I think is_numeric is a better choice, but this works too.
What I have above only matches floats, so they have to have the decimal. To make that optional use /^\d+(\.\d+)?$/ instead.
^ start of string
\d+ one or more digits
\. the dot, literally
\d+ one or more digits
$ end of string
For the second one /^\d+(\.\d+)?$/ it's the same as the above except with this addition:
(...)? optional capture group, match this pastern 0 or 1 times.
Which it should now be obvious is what makes the decimal optional.
Cheers!
maybe you would like to use the non-locale-aware floatval function:
float floatval ( mixed $var ) - Gets the float value of a string.
Example from the documentation:
$string = '122.34343The';
$float = floatval($string);
echo $float; // 122.34343

php for loop with decimal point [duplicate]

Simple maths:
$a=$b/$c; echo $a;
if $b equals to 123.00 and $c equals to 1 then $a becomes 123.
If $b is 123.50, $c is 1, $a is 123.50. But in the former case , I want $a to be 123.00.
It is possible to test whether $a has any non-zero fraction part or not, and then add the trailing zeros as necessary.
But I am looking for php functions to do the same thing. Possible?
EDIT :
What if I do not want the commas from number_format there ?
Use sprintf("%0.2f",$a);. docs
Use the number_format function. If you don't want comma separators, set all four parameters of the function like so (the thousands separator is the fourth parameter):
$number = number_format(1234, 2, '.', '');
Yup, using https://www.php.net/manual/en/function.number-format.php function like this:
$a = 123;
$answer = number_format($a,"2");
echo $answer;

PHP- Maintain leading 0 in number [duplicate]

I need to add numbers in php without changing the number format like below
$a = "001";
$b = "5";
$c = $a+$b;
Now the result comes like "6" but I need "006" if $a is "01" then the result should be "06".
Thanks
Technically speaking, the $a and $b in your example are strings - when you use the addition operator on them they converted to integers which can't retain leading zeroes. More details on string-to-number conversion are in the manual
Something like this would do it (assuming positive integer strings with leading zeros)
#figure out how long the result should be
$len=max(strlen($a), strlen($b));
#pad the sum to match that length
$c=str_pad($a+$b, $len, '0', STR_PAD_LEFT);
If you always know how long the string has to be, you could use sprintf, e.g.
$c=sprintf('%03d', $a+$b);
Here, % introduces a placeholder, 03 tells it we want zero padded to fill at least 3 digits, and d tells it we're formatting an integer.
Hope this would help you:
<?php
$a="001";
$b="5";
$l=max(strlen($a),strlen($b));
$c=str_pad($a+$b, $l,"0", STR_PAD_LEFT);
echo $c;
?>
For common case. Your code should looks like this.
$a = someFormat($original_a);
$b = someFormat2($original_b); // $b has different format.
$c = someFormat($a + $b);
Or, you need write formatRecognition function.
$a = getValueA();
$b = getValueB();
$c = someFormat(formatRecognition($a), $a + $b);

Adding comma and dot separated values in PHP

The current application I'm building needs to let the user enter values like "3,040,400.00".
I noticed that PHP doesn't know how to add or substract values with that format?
How can I perform this operations keeping in mind that the user will enter values formatted as above?
For example:
$a = '3,040,400.00';
$b = '23,949.00';
echo $a - $b; // returns -20
You should simply use str_replace() in order first to remove to commas inside the string. You cannot outright do arithmetic on them. Then after converting them properly you can use number_format() in the end. Consider this example:
$a = '3,040,400.00';
$b = '23,949.00';
$a = (float) str_replace(',', '', $a);
$b = (float) str_replace(',', '', $b);
$total = $a - $b;
echo number_format($total, 2, '.', ','); // should output : 3,016,451.00
Fiddle
$a = str_replace(",","",$a);
same for b
for outputting your values you can use the php-function number_format():
http://www.php.net/manual/en/function.number-format.php

PHP short sentence of stating new vairable

I wonder if there is any way can short sentence to state a variable.
Purpose: only for if you are in a situation have to state 20 variables at the time. more convenience
$a = 1; $b = 2;
//Imagination like below
$a, $b = 1, 2;
$a = 1, $b = 2;
Thank you very much for your advice of alternatives.
(If you do not have any ideas, please do not accuse the way of why have to think about this), because arrray, (object) are alternatives, but not match what I need on my question
The closest you can get to that syntax is using list():
<?php
list ($a, $b) = array(1, 2);
echo $a . ' ' . $b; // prints "1 2"
Its magic!
EDIT:
For even more magic, you can use short array notation from PHP 5.4 onwards:
<?php
list($a, $b) = [1, 2];
print $a . ', ' . $b; // prints 1, 2
How is $a = 1, $b = 2; shorter than $a = 1; $b = 2; ?
If for any reason you need two assignments in one statement, you could to it with list:
list($a,$b) = array(1,2);
However, shortening is not a valid reason for this.

Categories