Can't get string numbers to become float or integer PHP - php

I'm trying to parse a csv file with PHP and everything works ok as long as I keep the numbers as strings. However, since I'd like to sum the values of nested arrays I need them to be numbers.
There are three values that I need to fix:
$column[1] is cost and contains decimals (ex. 20.30)
$column[2] is clicks (ex. 15)
$column[3] is conversions (ex. 3)
If I try using floatval() or intval() on the values they return 0.
Example: $cost = intval($column[1]);
I saw somewhere in another thread that they use trim() or ltrim() to clean up the value. So I tried that on my numbers...
$cost = intval(trim($column[1]));
$clicks = intval(trim($column[2]));
$conversions = intval(trim($column[3]));
But that just gives me the first digit of the number, so I get this..
cost : 2 (instead of 20.30)
clicks : 1 (instead of 15)
conversions: 3 (is actually correct)
I've tried using both "." and "," as decimals.
Really can't figure this one out. Any help I can get is much appreciated!
Structure:
array(4) {
[0]=> string(21)"avslag l�n"[1]=> string(11)"31.32"[2]=> string(3)"1"[3]=> string(5)"0 "
}
array(4) {
[0]=> string(45)"l�na trots kronofogden"[1]=> string(11)"99.12"[2]=> string(3)"2"[3]=> string(5)"0 "
}
array(4) {
[0]=> string(59)"g�r gymnasiet men vill ta l�n"[1]=> string(11)"33.86"[2]=> string(3)"1"[3]=> string(5)"0 "
}
array(4) {
[0]=> string(45)"l�n till enskild firma"[1]=> string(11)"80.07"[2]=> string(3)"1"[3]=> string(5)"1 "
}

You could type cast the values as follows:
$cost = (double) $column[1];
$clicks = (int) $column[2];
$conversions = (int) $column[3];
http://www.php.net/manual/en/language.types.type-juggling.php
if you are looking to format the double then do the following:
$cost = number_format($column[1], 2);
EDIT: Thanks for the var_dump, try this.
$cost = (double) $column[0][1];
$clicks = (int) $column[0][2];
$conversions = (int) $column[0][3];
You are trying to interact with a 2D array as if it was 1 dimensional.

use number format with floatval
$cost = floatval(column[1]);
$cost = number_format($cost, 2);
http://php.net/manual/en/function.number-format.php

if value of $column[1] is "20.30" you can simply use it for calculations as php automatically converts string to numbers when you do arthritic calculations.
ex:
$column[1]="20.30";//$column[1] is string.
$column[1]*=1.0;//Now $column[1] is an float variable..
You can also use type conversion like:
$a=(float)$column[1]*1;
And so on..

I could be wrong...in which case I have a gambling problem apparently...but I'm fairly certain you're trying to do all these conversions on an actual array(), not a string.
Your printout shows 4 different arrays, each with key/value pairs. And all of these are linked into $column.
If I had to guess, which I shouldn't do on Stack Exchange, I would say try this:
$column[1][1]
instead of what you have now as
$column[1]
I've been up quite a long time though so grain of salts are to be taken here.

Related

How to calculate using a POST variable?

I need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800

rounding a number, NOT necessarily decimel PHP

I have a question.
I am using php to generate a number based on operations that a user has specified
This variable is called
$new
$new is an integer, I want to be able to round $new to a 12 digit number, regardless of the answer
I was thinking I could use
round() or ceil()
but I believe these are used for rounding decimel places
So, I have an integer stored in $new, when $new is echoed out I want for it to print 12 digits. Whether the number is 60 billion or 0.00000000006
If i understand correctly
function showNumber($input) {
$show = 12;
$input = number_format(min($input,str_repeat('9', $show)), ($show-1) - strlen(number_format($input,0,'.','')),'.','');
return $input;
}
var_dump(showNumber(1));
var_dump(showNumber(0.00000000006));
var_dump(showNumber(100000000000000000000000));
gives
string(12) "1.0000000000"
string(12) "0.0000000001"
string(12) "999999999999"

PHP: Max and Min returning incorrect results

I am sure this is because of the "g" on the end but this is the scenario and results when I try and work out a ratio percent. I always want to divide the highest of 2 numbers by the lowest.
$item1 = "200.00g";
$item2 = "50.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "400%"
$item1 = "100.00g";
$item2 = "5.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "2000%"
PROBLEM RESULT:
$item1 = "8.00g";
$item2 = "14.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "57%"
// I am expecting (14.00g / 8.00g)*100 = "175%"
It's type casting;
$item1 = "8.00";
$item2 = "14.00";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
result will be 175%
When you want to use your strings in mathematical operations, and you know that the unit is placed at the end as it is in your example, you can cast your variables to floats:
$item1_numeric = (float) $item1;
But obviously it is better to have the values and the units separated in your variables / database.
Use: substr($item1, 0, -1) instade of $item1, substr($item2, 0, -1) instade of $item2 when you do round.
You can't compare 2 strings with round().
Edit : If $item1 = "200g", ma solution is ok, but if if $item1 = "200.00g" you need to remove "." before round() with for example pregreplace.
Oh, YAPHPB - and one of my favorite ones. Even though it's written in the Doc:
When [max()] given a string it will be cast as an integer when comparing.
... it's only a partial truth: if at least one of compared values is a number, or a numeric string.
Otherwise all the strings will be compared as strings: first {0} characters of each strings will be compared, then {1}, then {2}... etc.
So basically that's what happens here:
echo max("200.00g", "50.00g"); // 50.00g, as '5' > '2'
echo max("200.00g", 50); // "200.00g", as it gets converted to int (become 200)
And that's even more crazy:
echo max("200.00g", "1000.00"); // "200.00g", as '2' > '1'
echo max("200.00", "1000.00"); // "1000.00", as we tried to help you, no, really!
The latter result can actually be predicted by someone knowing of numeric concept: when both strings are pure numbers, they got converted to numbers when compared. Still, I found this behavior unreliable, to say the least.
The bottom line: if you need to compare numbers, compare numbers, period. Type conversion in PHP can get real messy - and bite you in the bottom real hard when you least expect it. )

Calculating total price from string value in php

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.

Php set value as a number

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.

Categories