tags:

views:

41

answers:

2
+4  Q: 

PHP calculation

I'm trying to output a value from xml this is what I do -

<?php
 echo $responseTemp->Items->Item->CustomerReviews->AverageRating;
?>

This outputs 4.5, but when I change it to the code below it displays as 8. Why isn't it displaying as 9? Thanks.

<?php
echo $responseTemp->Items->Item->CustomerReviews->AverageRating*2;
?>
+5  A: 

Try casting the value to a numerical value first.

$num = (double) $responseTemp->Items->Item->CustomerReviews->AverageRating;

echo $num * 2;

See Type Juggling and String Conversion to Numbers on the PHP website for more information.

Jonathan Sampson
Thanks for the quick answer
usertest
You're more than welcome. Welcome to StackOverflow!
Jonathan Sampson
Yeah, if you are expecting a double, enforce that it will be.
Tchalvak
+2  A: 

If you are looking for a decimal value without doing typecasting, you have to multiply by a number with a decimal. Otherwise it will return a regular integer like the number you gave it.

Try multiplying by 2.0

echo $responseTemp->Items->Item->CustomerReviews->AverageRating*2.0;
Mike
Enforcing the expectation on the known number seems less useful than making sure that the variable is what you expect it to be, e.g. `echo (double) $responseTemp->Items->Item->CustomerReviews->AverageRating*2.0;`
Tchalvak
I know it's not proper, I was just offering another explanation as to why it wasn't working.
Mike