I have a php form thats capturing data, mostly strings, and submitting it to an XML file for storage.
I would like one of the inputs to to capture a price (float), and then subtract a percentage tied to that users account (stored in mysql), storing both values in the xml file.
the current code looks like this:
$price = $_POST['product_price'];
$our_price = $price - $user['product_fee'];
This obviously won't work because both values are being stored as strings, not floats.
There is an easy solution to this, I'm obviously missing something here.
You could use floatval to parse the strings as floats.
$price = floatval($_POST['product_price']);
$our_price = $price - floatval($user['product_fee']);
Warning: Read the WARNING in the php float page about precision!!!
Update:
To show two decimal points for the floating value, you could use the number_format() function as:
echo number_format(floatval($our_price), 2, '.', '');
but keep in mind that this function again returns a string, which is expected as it is for presentation purposes mostly. If you wanted you could use floatval again on the returned string to parse it as a float:
$new_float = floatval(number_format(floatval($our_price), 2, '.', ''));
Note: For number_format here we also passed 3 optional parameters after the float:
Number 2 -> for the number of decimals needed
A dot (.) which is the decimal separator, and
A comma (,) which is the thousands separator to be used if needed.
PHP is not very strict when it comes to data types. You should be able to subtract two strings (and yes, that is very weird). For example, this works perfectly fine:
$var = '100.00';
$var2 = '20.00';
var_dump($var - $var2);
That will return float(80) as a result.
But if the strings always represent float values, you could typecast them to be sure. Like:
$price = (float) $_POST['product_price'];
By putting (float) in front of the variable, you force $price to be a float value. You can do the same for the fee and then you should be able to subtract them.
PHP is quite tolerable in that way - it will analyze your variables and coerce their type to float automatically:
fike#v-lubuntu:~$ php -r 'var_dump("12.31" - "0.17");'
double(12.14)
As said above, you can use floatval() or type casting ($var = (float) $string) to perform type casting manually. What is 100% must be said is that you should be thousand times aware of what your variables will cast to, since this expression is perfectly valid and will return true:
true == 'true'
To force type checking, you need to use extra equal sign operator:
true === 'true' // false
true !== 'true' // true
Related
Suppose we have a string $str = "a"; and number $num = 2;
$str = 'a';
$num = 2;
echo $str*$num;
Output:
0
When performing arithmetic operations on a string operand, PHP will try to convert the string to a number.
It does this by looking for digits at the beginning of the string and will try to convert them into a value. If there are no digits, the value will be zero.
(There's an edge case for strings containing e or E (scientific notation), but that's not relevant here.)
Good Question.
Same i did ask to my teacher when i was in collage,
The answer is.
String * int= infinity; //According to scientific calculator answer is infinity.
but we need to continue our so program it provide 0.
it is made by code by default answer.
Simply said the string will be converted to an integer with a value of 0. This will include most of the cases when only alphabetic values are used. If you try to add a integer value at the beginning of the string it would in theory become a integer of that value.
I would recommend to read Why PHP Strings Equal Zero or Comparison Operators
Maybe you are looking for str_repeat, instead doing looping for that, its a default value that php serve to you, or you need to cast A into integer . When you try to do calculation for data that is not in Integer/float data type. Usually PHP auto-typecast the variables. In some cases it wont. Then we have to type cast it manually
$td = 4.0;
echo $td;
The output is 4;
But I want real number (4.0) in double data type;
First, not to be nitpicky, but PHP doesn't have the type you want*. When you do $td = 4.0; you have created a float.
If you inspect it with var_dump($td);, you'll see: float 4. Since there isn't really a concept of significant figures here, the zero after the decimal is not relevant to the stored value.
Second, when you do echo $td;, PHP will output the string representation of float 4. Again, without somehow specifying that you want to display n decimal places, PHP will omit any trailing zeroes. For another example, if you did this
$td = 4.00010000;
echo $td;
You'd see
4.0001
This is why the other answers/comments are guiding you toward a formatting solution. Because what you're really needing to do is not to change the type of the variable, because it's already stored in an appropriate type. You just need to specify how it should be displayed when it's converted to a string. There are different ways to do that. If you use printf, you can specify a number of decimal places to display. Here's how you make it show one, for example:
printf('%.1f', $td);
The '%.1f' is a format string. The .1 part is what tells it to show one decimal place. But you aren't changing the type. It's just output formatting.
*Here's a list of PHP's native types. And I was sort of mistaken, it does indicate that float is aka double.
You can use printf
echo printf("%f\n", $td);
Check this out -> string number_format ( float $number [, int $decimals = 0 ] )
Doc: http://php.net/manual/en/function.number-format.php
$td = 4.0;
echo number_format($td,1);
this will spit out 4.0 the "1" is the number of decimals you want in the number
In PHP I have the following code:
<?PHP
$var = .000021;
echo $var;
?>
the output is 2.1E-5 !
Why? it should print .000021
Use number_format() to get what you're after:
print number_format($var, 5);
Also check sprintf()
2.1E-5 is the same number as 0.000021. That's how it prints numbers below 0.001. Use printf() if you want it in a particular format.
Edit If you're not familiar with the 2.1E-5 syntax, you should know it is shorthand for 2.1×10-5. It is how most programming languages represent numbers in scientific notation.
Use number_format or sprintf if you want to see the number as you expect.
echo sprintf('%f', $var);
echo number_format($var, 6);
To show a number up to 8 decimal spaces, without extra zeroes to the right (as number_format does, which can be annoying), use this:
echo rtrim(rtrim(sprintf('%.8F', $var), '0'), ".");
In general, a number is a number, not a string, and this means that any programming language treats a number as a number. Thus, the number by itself doesn't imply any specific format (like using .000021 instead of 2.1e-5). This is nothing different to displaying a number with leading zeros (like 0.000021) or aligning lists of numbers. This is a general issue you'll find in any programming language: if you want a specific format you need to specify it, using the format functions of your programming language.
Unless you specify the number as string and convert it to a real number when needed, of course. Some languages can do this implicitly.
The previous answers responded to OP question, but none offered the code to do it.
Use this function to format any number with E- format.
function format_amount_with_no_e($amount) {
$amount = (string)$amount; // cast the number in string
$pos = stripos($amount, 'E-'); // get the E- position
$there_is_e = $pos !== false; // E- is found
if ($there_is_e) {
$decimals = intval(substr($amount, $pos + 2, strlen($amount))); // extract the decimals
$amount = number_format($amount, $decimals, '.', ','); // format the number without E-
}
return $amount;
}
Please note the function will always return a string.
Programming languages have different methods for storing numbers in memory. This is determined by the type of number that is being used. In your case, you have a floating point number (a fraction) that is to large to be stored as a fixed point number ( fractions are stored in this manner depending on their size).
This is a very important feature especially when working with very large or very small numbers. For instance, NASA or spaceX uses special storage methods for its calculations to ensure that the rockets the re-enter earths orbit land where they should.
Also, different storage methods take up different amounts of memory. However, the solution provided above should work. Just remember round off errors might occur with very big or small numbers.
I have a database that is ported from an XLS file. My numbers are in this form
3.41002E+13
But the readable form should be : 34100224263318
How can I convert the first form to the second?
Use number_format()
string number_format(float $number, int $decimals = 0, string $dec_point = '.', string $thousands_sep = ',' )
By default, thousands are seperated by ,, that's why you need to pass all four arguments:
number_format(3.41002E+13, 0, ".", "");
34100200000000
As you can see, you have an additional problem: You lose precision - sort of at least: It was never there in the first place.
You need to use number_format, check it out here
You will never be able to get the exact number (e.g. 34100224263318)
"Ex" stands for 10^x, which is used for numbers with a lot of digits as an approximation of the actual number.
number_format is what you can use to get the approximation in a standard human-readable numerical version (Ex is readable too, but anyway).
3.41002E+13 == 3.41002*10^13 == 3.41002 * 100000000000000
It is just a float type. If you want to achieve this you need to use number_format();
number_format(3.41002E+13) == 34100224263318
As phant0m commented if you use
number_format(1.11E-2) == 0,00111
but with integers you will be fine if you want a dot just use
number_format(1.11E-2, 5, '.', '') == 0.00111
When 10000-100, then result should be 9900.
I tried when I use:-
< ?php
$num1 = number_format(round(10000,1),2);
$num2 = number_format(round(100,1),2);
echo $num1 - $num2;
?>
The above result is -90, that made me realize that the number_format function is not applicable in calculations.
Would there be any way that I can convert a value of number_format (obtained from POST from a previous page) back to numerical value for normal calculation?
To start, the reason is that:
(int) "10,000.00"
resolves to 10 since it stops parsing at the first non-numeric character. Thanks to PHP's weird type system, this is done implicitly when you subtract the strings.
Yes, you can strip out the commas easily:
$unformatted = str_replace(",", "", $formatted);
but it's cleaner to just post the raw numeric value (you can still use number_format for the displayed value).
EDIT: It is good practice to explicitly convert numeric strings (without commas) to float (or int) with either a cast ((int) or (float)) or the function version (intval or floatval).
I don't think you can perform this 10,000.00 -100.00 with the comma in the equation. Just perform the raw arithmetic operation then format the answer.
$num1 = 10000;
$num2 = 100;
echo number_format(round($num1 - $num2,1),2);
This outputs
9,900.00
There is an easier way.
number_format is for fomating output numbers or to round easy numbers.
number_format gives us power to make well fomed rounded numbers, for a better user experience.
For calcualtion and saving Numbers in your MYSQL Database use this.
Save your Numbers in MYSQL always as type DECIMAL not FLOAT. There are lots of bugs if you want to calculate with FLOAT fields.
Than use the english notation.
$number = 1234.56;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', ''); //
// 1234.57
And now you can calculate and save it, without any Bugs.
Always Remember yourself, Saving numbers into $var is always a string.
Yeah, you can deifine type, but it doesn't matter in first case, and its to long to explain here.
For more information about number_format see here -> http://php.net/manual/en/function.number-format.php