A little help with making a result always 2 decimal places and showing the result

Hi All

I am a very beginner when it comes to jquery etc and am chuffed that I have managed to get me form working so far.

I have a form that when someone enters a value it automatically adds everything up… here is my code that is working fine:

            $('#groceries, #petrol').keyup(function(){
               var groceries = parseFloat($('#groceries').val()) || 0;
               var petrol = parseFloat($('#petrol').val()) || 0;
               $('#sum').val((groceries*0.05) + (petrol*0.05));

I need to show the result (sum) to 2 decimal places.

Can someone please let me know how I can do that.

Also the result is showing in a number input:

<input type="number" name="sum" id="sum" class="border-0" style="padding:0em; width:120px; font-weight:bolder;" placeholder="0" readonly>

I would LOVE to be able to echo the result in a <span> or something… I tried <span id="sum"></span> but that did not work.

Is this possible and how?

Thanks for any help.


If you were using vanilla JS you could use the toFixed method. I don’t know what the jQuery equivalent is.

You might find the toFixed method useful then, for that lets you round off a number to for example, two decimal places.

Although, because of many languages inability to add decimal values (thanks to binary limitations), you end up with much better and stable results by dealing with everything as cents. 500 cents for 5 dollars, etc.

Unfortunately it is not supported to have multiple unique identifiers with the same id, as that breaches the unique aspect.

You will need to use a different id, and update that from the script too with the appropriate value.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.