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
I have a problem with this function always my mt_rand() give me the same number:
$hex = 'f12a218a7dd76fb5924f5deb1ef75a889eba4724e55e6568cf30be634706bd4c'; // i edit this string for each request
$hex = hexdec($hex);
mt_srand($hex);
$hex = sprintf("%04d", mt_rand('0','9999'));
$hex is always changed, but the result is always the same 4488.
Edit
$hex = str_split($hex);
$hex = implode("", array_slice($hex, 0, 7));
mt_srand($hex);
$number = sprintf("%04d", mt_rand('0','9999'));
http://php.net/manual/en/function.mt-srand.php
Your problem is, that you always end up with a float value in your variable $hex. And the function mt_srand() as you can also see in the manual:
void mt_srand ([ int $seed ] )
Expects an integer. So what it does is, it simply tries to convert your float value to an integer. But since this fails it will always return 0.
So at the end you always end up with the seed 0 and then also with the same "random" number.
You can see this if you do:
var_dump($hex);
output:
float(1.0908183557664E+77)
And if you then want to see in which integer it will end up if it gets converted you can use this:
var_dump((int)$hex);
And you will see it will always be 0.
Also if you are interested in, why your number ends up as float, it's simply because of the integer overflow, since your number is way too big and accoding to the manual:
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.
And if you do:
echo PHP_INT_MAX;
You will get the max value of int, which will be:
28192147483647 //32 bit
9223372036854775807 //64 bit
EDIT:
So now how to fix this problem and still make sure to get a random number?
Well the first thought could be just to check if the value is bigger than PHP_INT_MAX and if yes set it to some other number. But I assume and it seems like you will always have such a large hex number.
So I would recommend you something like this:
$arr = str_split($hex);
shuffle($arr);
$hex = implode("", array_slice($arr, 0, 7));
Here I just split your number into an array with str_split(), to then shuffle() the array and after this I implode() the first 7 array elements which I get with array_slice().
After you have done this you can use it with hexdec() and then use it in mt_srand().
Also why do I only get the first 7 elements? Simply because then I can make sure I don't hit the PHP_INT_MAX value.
If I have, say, 8.1 saved as a string/plaintext, how can I change that into the integer (that I can do addition with) 81? (I've got to remove the period and change it into an integer. I can't seem to figure it out even though I know it should be simple. Everything I try simply outputs 1.)
You can also try this
$str = '8.1';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo $int; // 81
echo $int+1; // 82
DEMO.
If you're dealing with whole numbers (as you said), you could use the intval function that is built into PHP.
http://php.net/manual/en/function.intval.php
So basically, once you have your string parsed and setup as a whole number you can do something like:
intval("81");
And get back the integer 81.
Example:
$strNum = "81";
$intNum = intval($strNum);
echo $intNum;
// "81"
echo getType($intNum);
// "integer"
Since php does auto-casting, this should work:
<?php
$str="8432.145522";
$val = str_replace('.','', $str);
print $str." : ".$val;
?>
Output:
8432.145522 : 8432145522
Not sure if this will work. But if you always have something.something,(like 1.1 or 4.2), you can multiply by 10 and do intval('string here'). But if you have something.somethingsomething or with more somethings(like 1.42 and 5.234267, etc.), I don't know what to say. Maybe a function to keep multiplying by ten until it's an integer with is_int()?
Sources:
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.is-int.php
Convert a string to a double - is this possible?
If I have a variable in PHP containing 0001 and I add 1 to it, the result is 2 instead of 0002.
How do I solve this problem?
$foo = sprintf('%04d', $foo + 1);
It would probably help you to understand the PHP data types and how they're affected when you do operations to variables of various types. You say you have "a variable in PHP say 0001", but what type is that variable? Probably a string, "0001", since an integer can't have that value (it's just 1). So when you do this:
echo ("0001" + 1);
...the + operator says, "Hm, that's a string and an integer. I don't know how to add a string and an int. But I DO know how to convert a string INTO an int, and then add two ints together, so let me do that," and then it converts "0001" to 1. Why? Because the PHP rules for converting a string to an integer say that any number of leading zeroes in the string are discarded. Which means that the string "0001" becomes 1.
Then the + says, "Hey, I know how to add 1 and 1. It's 2!" and the output of that statement is 2.
Another option is the str_pad() function.
$text = str_pad($text, 4, '0', STR_PAD_LEFT);
<?php
#how many chars will be in the string
$fill = 6;
#the number
$number = 56;
#with str_pad function the zeros will be added
echo str_pad($number, $fill, '0', STR_PAD_LEFT);
// The result: 000056
?>
I am not familiar with PHP at all and had a quick question.
I have 2 variables pricePerUnit and InvoicedUnits. Here's the code that is setting these to values:
$InvoicedUnits = ((string) $InvoiceLineItem->InvoicedUnits);
$pricePerUnit = ((string) $InvoiceLineItem->PricePerUnit);
If I output this, I get the correct values. Lets say 5000 invoiced units and 1.00 for price.
Now, I need to show the total amount spent. When I multiply these two together it doesn't work (as expected, these are strings).
But I have no clue how to parse/cast/convert variables in PHP.
What should I do?
$rootbeer = (float) $InvoicedUnits;
Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.
You want the non-locale-aware floatval function:
float floatval ( mixed $var ) - Gets the float value of a string.
Example:
$string = '122.34343The';
$float = floatval($string);
echo $float; // 122.34343
Well, if user write 1,00,000 then floatvar will show error. So -
floatval(preg_replace("/[^-0-9\.]/","",$input));
This is much more reliable.
Usage :
$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));
Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2:
1,000.46
But in Germany you would change comma and point:
1.000,46
This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure of the Zend Framework for this task. This component will parse the string to a float by the users language.
you can follow this link to know more about How to convert a string/number into number/float/decimal in PHP.
HERE IS WHAT THIS LINK SAYS...
Method 1: Using number_format() Function. The number_format() function is used to convert a string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.
$num = "1000.314";
//Convert string in number using
//number_format(), function
echo number_format($num), "\n";
//Convert string in number using
//number_format(), function
echo number_format($num, 2);
Method 2: Using type casting: Typecasting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.
// Number in string format
$num = "1000.314";
// Type cast using int
echo (int)$num, "\n";
// Type cast using float
echo (float)$num, "\n";
// Type cast using double
echo (double)$num;
Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.
// Number in string format
$num = "1000.314";
// intval() function to convert
// string into integer
echo intval($num), "\n";
// floatval() function to convert
// string to float
echo floatval($num);
Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.
// Number into string format
$num = "1000.314";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0, "\n";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.0, "\n";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.1;
Use this function to cast a float value from any kind of text style:
function parseFloat($value) {
return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}
This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values.
You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)
I was running in to a problem with the standard way to do this:
$string = "one";
$float = (float)$string;
echo $float; : ( Prints 0 )
If there isn't a valid number, the parser shouldn't return a number, it should throw an error. (This is a condition I'm trying to catch in my code, YMMV)
To fix this I have done the following:
$string = "one";
$float = is_numeric($string) ? (float)$string : null;
echo $float; : ( Prints nothing )
Then before further processing the conversion, I can check and return an error if there wasn't a valid parse of the string.
For the sake of completeness, although this question is ancient, it's worth mentioning the filter_var() set of functions, which should not only handle the formatting bits itself, but also validate or sanitise the output, thus being safer to use in the context of a form being filled in by users (or, eventually, a database that might have some corrupted/inconsistent fields):
$InvoicedUnits = (float) filter_var($InvoiceLineItem->InvoicedUnits,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$pricePerUnit = (float) filter_var($InvoiceLineItem->PricePerUnit,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
printf("The total is: %.2f\n", $InvoicedUnits * $pricePerUnit); // both are now floats and the result is a float, formatted to two digits after the decimal sign.
This sanitises the output (which will still remain a string) and will accept the current locale's setting of the decimal separator (e.g. dot vs. comma); also, there are more options on the PHP manual for validation (which will automatically convert the result to a float if valid). The results will be slightly different for different scenarios — e.g. if you know in advance that the $InvoiceLineItem will only have valid digits and symbols for floating-point numbers, or if you need to 'clean up' the field first, getting rid of whitespace, stray characters (such as currency symbols!), and so forth.
Finally, if you wish to have nicely-formatted output — since the total is expressed in a currency — you should also take a look at the built-in NumberFormatter class, and do something like:
$InvoicedUnits = (float) filter_var($InvoiceLineItem->InvoicedUnits,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$pricePerUnit = (float) filter_var($InvoiceLineItem->PricePerUnit,
FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$fmt = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'Total is: ' . $fmt->formatCurrency($InvoicedUnits * $pricePerUnit, 'EUR') . PHP_EOL;
This will also handle thousand separators (spaces, dots, commas...) according to the configured locale, and other similar fancy things.
Also, if you wish, you can use '' (the empty string) for the default locale string (set either by the server or optionally by the browser) and $fmt->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL) to get the default 3-letter currency code (which might not be what you want, since usually prices are given in a specific currency — these functions do not take currency exchange rates into account!).
If you need to handle values that cannot be converted separately, you can use this method:
try {
// use + 0 if you are accounting in cents
$doubleValue = trim($stringThatMightBeNumeric) + 0.0;
} catch (\Throwable $th) {
// bail here if you need to
}