As an example I have code similar to this:
$r1 = 7.39999999999999;
$r2 = 10000;
echo bcmul($r1,$r2,100);
//returns 74000.0
echo ($r1*$r2);
//returns 74000.0
I am wanting it to return 73999.9999999999 rather than rounding it off.
Is there a formula or function to do this?
The doc http://php.net/manual/de/function.bcmul.php says:
left_operand: The left operand, as a string.
right_operand: The right operand, as a string.
So use strings instead:
$r1 = "7.39999999999999";
$r2 = "10000";
echo bcmul($r1,$r2,100);
works.
Or if you have these varibales from somewhere cast them (via (string) ) to string. Maybe at this step you could encounter some roundings already...
I'm not a php person, but a quick Google suggests you may want the
$number_format()
function and specify the $decimals parameter. See this link
Related
I am trying to compare 2 values in PHP.
My logic is:
I have a remaining amount (a)
I have a amount to be charged (b)
I calculate remaining to be by ( a - b )
After charge action I get the actual remaining value (c)
I compare the value I got in #3 with (c)
Even though the both are similar PHP says they are not equal.
Below given is my code (with filled values)
<?php
$remaining_amount_before_payment = "600";
$remaining_amount_after_payment = (float)$remaining_amount_before_payment - (float)"387.60";
$actual_remaining_amount_after_payment = "212.4";
echo "actual_remaining_amount_after_payment: {$actual_remaining_amount_after_payment} <br><br>";
echo "remaining_amount_after_payment: {$remaining_amount_after_payment} <br><br>";
var_dump( ((float)$actual_remaining_amount_after_payment) == ((float)$remaining_amount_after_payment) );?>
I type cast the values to float, but the var_dump returns FALSE.
Can anybody help me to find out why this is?
I am using PHP 5.6.
Thanks in advance!
Bingo!
After several attempts I caught the catch. I was going crazy.
The "problem" is inside the right rounding values
$remaining_amount_before_payment = floatval("600"); // use floatval istead of (float)
$remaining_amount_after_payment = round($remaining_amount_before_payment - floatval("387.60"), 2);// use floatval istead of (float) and round result
$actual_remaining_amount_after_payment = floatval("212.4");// use floatval
echo "actual_remaining_amount_after_payment: {$actual_remaining_amount_after_payment} <br><br>";
echo "remaining_amount_after_payment: {$remaining_amount_after_payment} <br><br>";
var_dump( $actual_remaining_amount_after_payment === $remaining_amount_after_payment ); // return TRUE
Example
VoilĂ !
Use var_dump(abs(floatval($actual_remaining_amount_after_payment) == floatval($remaining_amount_after_payment)) == 0);
acual your variable '$remaining_amount_after_payment' is not realy 212.4
use a var_export to determine its value.
In my concern, You should "round" your floats values to a precision. round(x, precision) for comparison
I have a e-commerce shop and on the shopping cart page it gives me a separate price for every product, but I need total price.
in order to do that, I need to calculate all these values together and that's fine.
But, what bugs me is that I should calculate the sum of variables that are given in this format:
$455.00
What is the best way to extract the value "455" so I could add it to another value afterwards?
I hope I made myself clear...
Don't use float, but instead use an integer in cent. Floats are not precise (see Floating Point Precision), so the calculation tend to fail if you use floats. That's especially a burden if it is related to payments.
$str = '$455.00';
$r = sscanf($str, '$%d.%d', $dollar, $cent);
if ($r <> 2 or $cent > 99 or $cent < 0 or $dollar > 9999 or $dollar < 0) throw new Exception(sprintf('Invalid string "%s"', $str));
$amountInDollarCents = $dollar * 100 + $cent;
echo $str, ' -> ', $amountInDollarCents;
Demo
If you need only the dollar sign removed, use str_replace. To convert that to int or float, typecast it. However, using float results in non-exact calculations so be careful with it!
$newval = (int)str_replace('$', '', '$455.00');
I think that your ECommerce site only has $ (USD)
$price= substr($string_price,1);
This will convert your string to a float:
$price = (float)substr("$455.00", 1);
echo($price);
For more information, you can see this answer, which has a couple of good links for you in it.
What about the following:
$amount = array();
$amount[0] = '$455.15';
$amount[2] = '$85.75';
$total = 0;
foreach ($amount AS $value) {
$value = str_replace('$', '', $value);
$total += $value;
}
echo $total . "\n";
The cleaning operation is:
$value = str_replace('$', '', $value);
You might want to extract it in a function, especially if you need to use it in more than one place.
Another thing to think about is, why do you have the value in such way? It's a display format and such conversion should be the last to be done, ideally by the template. Maybe, if possible, you should consider to fix the code before, instead of applying a patch like this one.
It really looks like your program is doing it wrong. You should really represent all prices as (double) instead of a string. Then only when you need to show the price to the user you would prepend the $ sign to it, converting it to a string. But your program should really treat prices as numbers and not strings.
If you storing your price in the database as a string "$5.99" then you are really doing it wrong.
It's been a long time since I worked with PHP, so I don't know what the best practice would be for working with currency. One quick method would be to remove "$" and ".", and just add together the resulting as integers.
use str_replace() for instance, and replace "$" and "." with an empty string: http://se2.php.net/manual/en/function.str-replace.php
This will give you the whole sum in cents (thus avoiding some potential rounding problems). You can then divide it by 100 and format it however you like to display the sum as dollars.
How do I output a value as a number in php? I suspect I have a php value but it is outputting as text and not as a number.
Thanks
Here is the code - Updated for David from question below
<?php
if (preg_match('/\-(\d+)\.asp$/', $pagename1, $a))
{
$pageNumber = $a[1];}
else
{ // failed to match number from URL}
}
?>
If I call it in: This code it does not seem to work.
$maxRows_rs_datareviews = 10;
$pageNum_rs_datareviews = $pagename1; <<<<<------ This is where I want to use it.
if (isset($_GET['pageNum_rs_datareviews'])) {
$pageNum_rs_datareviews = $_GET['pageNum_rs_datareviews'];
}
If I make page name a static number like 3 the code works, if I use $pagename1 it does not, this gives me the idea $pagename1 is not seen as a number?
My stupidity!!!! - I used $pagename1 instead of pageNumber
What kind of number? An integer, decimal, float, something else?
Probably the easiest method is to use printf(), eg
printf('The number %d is an integer', $number);
printf('The number %0.2f has two decimal places', $number);
This might be blindingly obvious but it looks like you want to use
$pageNum_rs_datareviews = $pageNumber;
and not
$pageNum_rs_datareviews = $pagename1;
echo (int)$number; // integer 123
echo (float)$number; // float 123.45
would be the easiest
I prefer to use number_format:
echo number_format(56.30124355436,2).'%'; // 56.30%
echo number_format(56.30124355436,0).'%'; // 56%
$num = 5;
echo $num;
Any output is text, since it's output. It doesn't matter what the type of what you're outputting is, since the human eye will see it as text. It's how you actually treat is in the code is what matters.
Converting (casting) a string to a number is different. You can do stuff like:
$num = (int) $string;
$num = intval($string);
Googling php string to number should give you a beautiful array of choices.
Edit: To scrape a number from something, you can use preg_match('/\d+/', $string, $number). $number will now contain all numbers in $string.
get this from my database:
252.587254564
Well i wanna remove the .587254564 and keep the 252, how can i do that?
What function should i use and can you show me an example?
Greetings
You can do it in PHP:
round($val, 0);
or in your MYSQL statement:
select round(foo_value, 0) value from foo
You can do a simply cast to int.
$var = 252.587254564;
$var = (int)$var; // 252
As Tricker mentioned you can round the value down or you can just cast it to int like so:
$variable = 252.587254564; // this is of type double
$variable = (int)$variable; // this will cast the type from double to int causing it to strip the floating point.
In PHP you would use:
$value = floor($value);
floor: Returns the next lowest integer value by rounding the value down if necessary.
If you wanted to round up it would be:
$value = ceil($value);
ceil: Returns the next highest integer value by rounding the value up if necessary.
You can just cast it to an int:
$new = (int)$old;
Convert the float number to string, and use intval to convert it to integer will give you 1990
intval(("19.90"*100).'')
Before using above answer what is your exact requirement please see bellow example output.
$val = 252.587254564;
echo (int)$val; //252
echo round($val, 0); //253
echo ceil($val); //253
$val = 1234567890123456789.512345;
echo (int)$val; //1234567890123456768
echo round($val, 0);//1.2345678901235E+18
echo ceil($val); //1.2345678901235E+18
$val = 123456789012345678912.512345;
echo (int)$val; //-5670419503621177344
echo round($val, 0);//1.2345678901235E+20
echo ceil($val); //1.2345678901235E+20
you can use echo (int) 252.587254564;
positive number:
round(252.587254564) // 253
floor(252.587254564) // 252
ceil(252.587254564) //252
(int)252.587254564 // 252
intval(252.587254564) // 252
~~252.587254564 // 252
negative number:
round(-252.587254564) // -253
floor(-252.587254564) // -253
ceil(-252.587254564) // -252
(int)-252.587254564 // -252
intval(-252.587254564) // -252
~~-252.587254564 // -252
if you want just remove decimals without round you can use one of above codes except round and floor(for negative number).
But I recommended the last one, it's simpler and faster using prefix ~~
And there is also a not quite advisable method:
strtok($value, ".");
This cuts of the first part until it encounters a dot. The result will be a string, not a PHP integer. While it doesn't affect using the result much, it's not the best option.
I see many answers, but the question is:
"Well i wanna remove the .587254564 and keep the 252, how can i do
that?"
Since the questioner is asking for php, the function in php will be the one for the job.
$newValue = floor($value);
In MySQL you can use:
select floor(field)
or in PHP you can use:
floor($value);
I have a variable that is definited by a POST call from a form where it is inputed into a text field. Is there any way to convert this variable to an interger?
From the form:
Lenght: <input name="length" value="10" type="text" id="lenght" size="2" />
From the php code:
$length = $_POST['lenght'];
$url = substr($url, 0, $length);
This doesn't seem to work and the only reason why I think it isn't working is because $lenght is defined as text and not an interger.
Two things:
It doesn't work because you misspelled length <-> lenght
The correct way to convert a string to an integer is using the function intval.
$length = intval($_POST['length']);
$url = substr($url, 0, $length);
It likely doesn't work because you misspelled length twice, instead of zero or three times.
Seems to be a spelling error in your code: length vs. lenght - that could be your problem right there.
To do an explicit conversion, use the intval() function
$length = intval($_POST['length']);
Ignoring the misspellings of 'length' above, there are a few ways to explicitly convert a string into an integer in PHP. Usually this conversion will happen automatically. Take the following code:
$numeric_string = '42';
echo ($numeric_string * 2);
This will print out "84", as expected. See the reference on Type-Juggling.
If you KNOW that the string you have is a number (perhaps by checking is_numeric()) then you can either cast the variable to an Integer
$numeric_string = '42';
$converted_integer = (int) $numeric_string;
// or
$converted_integer = (integer) $numeric_string;
or use intval()
$numeric_string = '42';
$converted_integer = intval($numeric_string);
An important point to remember about intval() is that it will return a 0 if it can't resolve the string into an Integer. This could (potentially) give you a second way to check for errors (after is_numeric()), or it could cause unexpected results if you aren't properly insuring that the variable is numeric to begin with.
If you are sure that the value you are looking at has a correct representation for the type you want to convert to, you can also use a vanilla type cast operation:
$int = (int) "1"; // var_dump($int) => int(1)
$float = (float) "1.2345"; // var_dump($float) => float(1.2345)
Beware of incorrect representations of the variable that you are converting though, i.e casting "a random string" to a number might not yield the results you expect. If you are handling user input, you're better of using the above suggested solutions with function calls such as intval and floatval
That is because the PHP Web Server uses the name tag instead of the id tag. Even though the id is lenght, the name tag also has to be lenght, or it will malfunction.