javascriptphphtmldecimalrounding

Calculating VAT & Gross amounts from an onchange event


I have a php input form that I enter a 'Net Price' into mysql.

I have a seperate page that pulls that data into a table in a 'Quotations' page via echo.

I am trying to automatically calculate VAT and Total amounts from the 'Net Price', which I can do via

$row["Net_Price"]*0.2 

and

$row["Net_Price"]*1.2 

but I cannot get it to display to only 2 decimal places (always shows 3).

Have tried adding javascript to the <td> through research on here like this:

echo"<td onchange='(function(el){ el.value=parseFloat(el.value).toFixed(2);})(this)'>£ " . $row["Net_Price"]*0.2. "</td>";

Unsure if this is an impossible method, or if I should be attacking this differently, so help is appreciated.


Solution

  • onchange is called when the HTML changes after having been rendered on the client side,
    which can be useful for example for a dynamic text input in the HTML page but is of no use here,
    because your value is considered static HTML once PHP (on the server side) has created the HTML page by assembling HTML snippets with data from the database, and sent it to the client where it doesn't change anymore.

    So you will have to do your formatting during the PHP step.
    Fortunately PHP has the sprintf() formatting function,
    that you can use with the %.2f format: %f means a field of type floating point, and the .2 inbetween means that after the . you want exactly 2 digits.

    echo"<td>£ " . sprintf("%.2f", $row["Net_Price"]*0.2) . "</td>";