I am trying to make this calculation in php but is giving me wrong result. I think that is right.
And if i do 5000.00 - 100.10 it works, but i want the 5,000.00 to work too.
This is my code:
To create the 5,000.00 i have used number_format(5000, 2).
Aswell to the 100.10
$total = $value1 - $value2;
echo $total;
?>
$total = -95.00
I am trying to make this calculation in php but is giving me wrong result. I think that is right.
And if i do 5000.00 - 100.10 it works, but i want the 5,000.00 to work too.
Please Help...
If you want to do arithmetic on number, you can't have the thousands separator (,). What's happening is 5,000.00 is being read as 5 (it stops interpreting it as a number as soon as it hits the comma) and then you're getting 5 - 100.10 which is -95.10 (I'm thinking you left off the .10 in your example.
You'll need to convert first:
$value1 = floatval(str_replace(',', '', $original_value1))
$value2 = floatval(str_replace(',', '', $original_value2))
I'm assuming here that you have them as strings originally. These remove the comma separator.
It sounds like you're confusing rendering in the UI with calculations.
It's perfectly reasonable for a user to see currencies rendered according to their locale rules (e.g. a String "$1,000.00" in USA), but the calculations in the back need to done on a floating point number (e.g. 1000.0).
So you have to be able to convert back and forth between them. You can't make arithmetic operations work on a String. Better to parse the String to a float, do the operations, then convert that back to String for rendering.
Related
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.
In php I want some calculation part to be done. So I am getting all the values from variable and doing calculation. When doing calculation my formula is something like this
ceil($99.00/100)*2
but here it is showing error as $(dollar currency symbol is there). So can someone kindly tell me what is the good method of doing calculation here?
You need to learn basic PHP. You can't feed a monetary string (99 dollars and zero cents) into math operation. PHP will attempt to use $99 as a variable, and variables cannot be named with numbers.
You're basically doing
ceil (99 dollars concatenated with (zero divided by one hundred)) times two
If you're trying to do actual math with numbers, then
ceil(99/100) * 2
is all you'd need.
So basically you are dividing 99 dollars 0 cents with one hundred and multiplying the result by 2.
Try this:
<?php
$amount = 99.00;
$calculation = ($amount/100)*2;
echo $calculation;
You should append the dollar sign after you have done the calculation. Like this:
echo '$'.$calculation;
Remove the $. PHP can't calculate with anything but pure numbers, so $99.00 obviously won't work for 99 dollars.
Actually, what PHP thinks you are trying to do is have a variable (variable names start with a $). But 99 is not a valid variable name. Then PHP thinks you want to concatenate that variable with the result of 0 / 100 (concatenation is done with ..
Maybe the question is simple, but I can't find the answer.
What I need to do is to round number to 2 places after comma.
Im using this:
round(($data/$count*100), 2)
And when I get number like:
60.36036036036012 and : 37.83783783783808 is OK, because it's: 60.36 and 37.84
But why this:
1.8018018018018036
Is rounded to this:
1.8000000000000003
How to round always to 2 places, after comma?
You should get 1.8 unless you use something like old PHP version with some sort of related bugs. Still, if you want to see 1.80 you need to format output string, otherwise trailing zero will be stripped by default. The most flexible approach would be to use sprintf() formatting, like this:
$val = 1.8000000000000003;
printf("%.02f", round( $val, 2 ));
which would produce
1.80
The key is "%.02f" which means you want to format (f)loating point value, with two digits after dot, padded with 0 when needed (like this case).
See the sprintf() docs for more about available formatting possibilites.
Use PHP NumberFormatter class http://es.php.net/manual/es/class.numberformatter.php
I have a loop that calculates a couple revenue values then adds them together, like this:
$SalesGrowth = $C2012Sales+$C2011Sales;
In some cases, this works, and I get the expected, e.g.: 761.9 + 759.0 = 1520.9
In others, it looks like PHP randomly decides to round incorrectly (??) AND change the units (??) and I get:
8,788.0 + 8,794.3 = 16
What is going on here? I've even tried echoing out the separate sales values separated by a space, and they show up correctly, so the underlying figures aren't wrong.
Interpreted as a number, 8,788.0 is just 8, and parsing stops at the comma.
You'll need some locale-aware number parsing if you want to allow gimmicks like thousands-separators.
Update: If you have the Zend Framework, you can do this:
require_once('Zend/Locale/Format.php');
$locale = new Zend_Locale('en_GB'); // #1
$v = "8,410.5";
$n = Zend_Locale_Format::getNumber($v, array('locale' => $locale,'precision' => 3));
echo 2 * $number; // prints "16821"
Instead of hard-coding the locale, you could try and take it from the environment: new Zend_Locale(setlocale(LC_ALL, ""))
Dude the comma issue....
remove all the commas from the numbers before adding them...
str_replace(",","",$no1);
This is pretty simple... When you ask PHP to use the + operator, it will implicitly convert these strings such as "8,788.0" to an numeric value. Since you have a , character, it terminates the usefulness of the number, and it results in it being interpreted as 8. And so on...
Get rid of the non [0-9.] characters and it will work better.
Notice that 761.9 is a valid number, while 8,788.0 is not (from PHP's point of view).
So 8,788.0 in number context will evaluate as 8, just like 8,794.3. And 8+8 = 16.
To fix this problem, process your data to make numbers formatted properly.
I'm trying to do an echo of a variable containing 1400000.
so there is written: echo round(1400000);
this gives 1,4E+6 instead of the full number.
Anybody an idea on how to display it fully?
It seems that round was the problem.
I changed it with number_format() and this does the job just fine.
Thanks Aron and Paul for the answers.
Related to your question, I also came across this comment on the PHP website.
PHP switches from the standard decimal
notation to exponential notation for
certain "special" floats. You can see
a partial list of such "special"
values with this:
for( $tmp = 0, $i = 0; $i < 100; $i++ )
{
$tmp += 100000;
echo round($tmp),"\n";
}
So, if you add two floats, end up with
a "special" value, e.g. 1.2E+6, then
put that value unmodified into an
update query to store the value in a
decimal column, say, you will likely
get a failed transaction, since the
database will see "1.2E+6" as varchar
data, not decimal. Likewise, you will
likely get an XSD validation error if
you put the value into xml.
I have to be honest: this is one of
the strangest things I have seen in
any language in over 20 years of
coding, and it is a colossal pain to
work around.
It seems there has not been a "real" fix yet, but judging from the comments in the bug report Paul Dixon referered to earlier, his solution seems to work.
Possibly related to this bug report, so you could try
printf("%d", $myvar);