0

On my leaderboard here: https://mgo.io/mgo3/leaderboard.php , I am calculating the win % of a clan via this code:

<td style="text-align: center;">
  {% set total = leader['win'] + leader['loss'] %}
  {% if total == 0 %}0{% else %}{{ (leader['win'] / total * 100)|e }}{% endif %}%
</td>

The bracketed text info EX: {{ leader['xxx']|e }} is being passed through a .php file here:

function getLeaders() {
    global $dbh;

    date_default_timezone_set('UTC');

    $res = array();

    $stmt = $dbh->prepare("SELECT id, name, wins, losses, cp FROM clans ORDER BY id ASC");
    $stmt->execute();
    while ($row = $stmt->fetch()) {
        $clan_id = (int) $row['id'];
        $clan_name = $row['name'];

        $res[$clan_id] = array();
        $res[$clan_id]['name'] = $clan_name;
        $res[$clan_id]['rank'] = 0;
        $res[$clan_id]['cp'] = $row['cp'];
        $res[$clan_id]['win'] = $row['wins']; 
        $res[$clan_id]['loss'] = $row['losses'];

How would I shorten the percentage that is outputted from the formula to the tenth place? ex: 79.45653355% to 79.4%

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
D. George
  • 21
  • 2

1 Answers1

0

In PHP, use number_format($number, 2, '.', '') to format numbers.

dz902
  • 4,782
  • 38
  • 41
  • Yes, but I am trying to round the number to the 10th place sorry, I didnt mention that – D. George Apr 11 '16 at 03:23
  • @D.George You mean `round($var, $precision)`? – dz902 Apr 11 '16 at 03:35
  • It isn't working because I'm not sure what to put for $var since in the .php file the bracketed text is passed to the html and there it is used in the formula I show above and when i put the text there in the php file, it simply breaks the page – D. George Apr 11 '16 at 04:00
  • @D.George Move the calculation part `(leader['win'] / total * 100)` to PHP, like `$res[$clan_id]['percentage'] = (leader['win'] / total * 100);` then apply `round()` on it. Template for rendering the calculated variable only. – dz902 Apr 11 '16 at 04:03
  • Did that, and got this error: [phpBB Debug] PHP Warning: in file /home/phant0m/mgo.io/mgo3/api/leaderboard.php on line 27: Division by zero .. – D. George Apr 11 '16 at 04:35
  • I then tried to define total as a variable using var total = etc etc but that broke the page – D. George Apr 11 '16 at 04:37