-2

how to implement calculation of percents:

$x=3;
$y = 100\$x;  // 3.333..
$x*$y  - and here I need to get 100 without Observational error

Any ideas?

3
  • 100\$x? that's not division... it's a namespace reference, and invalid to boot. calculating a percentage is just basic math. the fact that you're using php (or any other language) doesn't change how you calculate a percentage...
    – Marc B
    Feb 14, 2013 at 17:05
  • 4
    100 / 3 is not 3.33333 to begin with...
    – Wooble
    Feb 14, 2013 at 17:07
  • echo 100 == ceil($x*$y); is THAT what you're asking for?
    – itsid
    Feb 14, 2013 at 17:24

1 Answer 1

55

Your backslash (\) is not the division symbol. You must use division / symbol.

Here's an example using number_format() which will round to two decimal places (the hundredths position).

$x = 3;
$y = 15;

$percent = $x/$y;
$percent_friendly = number_format( $percent * 100, 2 ) . '%'; // change 2 to # of decimals
1
  • You should check if $x > 0...
    – Abbas Arif
    Mar 26, 2021 at 21:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.