Pablo Servin Pablo Servin - 6 months ago 12
PHP Question

round 2 decimals in a multiplication php is not rounding

I come to you looking for answers, I have a table and I am calculating the tax field multiplying 1 variable per 0.16 but I want it to have just 2 decimals, not 10 or 4 or 3, I was trying with round() and with number_format() but is not working, there must be something I am doing wrong, how it suppose that I need to do it ?

I am showing the code

$html .= '<tr>
<td>'.escape($r->tecnologia).'</td>
<td>'.escape($r->normaespecificacion).'</td>
<td><img src="functions/'.escape($r->foto).'"></td>
<td>'.escape($r->marca).'</td>
<td>'.escape($r->modelo).'</td>
<td>'.escape($r->descripcion).'</td>
<td>$'.escape($r->preciounitario).'</td>
<td>$'.escape($r->number_format(preciounitario*0.16,2)).'</td> //this is the one with the error
<td>$'.escape($r->instalacion).'</td>
<td>$'.escape($r->totalcosto).'</td>
<td>'.escape($r->garantia).'</td>
<td>'.$listNum[$i].'</td>
</tr>';
$totalV += $listNum[$i]*$r->totalcosto;
$i = $i+1;
}

Answer

If you are just looking to round a number, then here is the solution:

<?php
    $number = 1353.234242;
    $rounded = (float)sprintf('%.2f', $number);
    echo $rounded; // will display 1353.23
Comments