Displaying full prize with two decimals at all times in a form

Hi Campers.

In November last year I posted a question in the forum about using forms in to populate a form.

Since then I have been coding away on my own and I have come pretty far. I have a page that pretty much works the way I intended . But do have a problem with decimal. As I need to have a prize displayed I want to have two decimals displayed at all times. Either 8.50 or 9.00 for example.

Please see my pizza project here.

I now use jQuery for the DOM Manipulation. For example the prize on the Pizza of the House works like this.

  • In a JSON, file I have the whole menu stored. Each pizza being an object, and in this case prize: 5.00
  • In the JavaScript file I loop trough the JSON, including the Pizza of the House and its prize. $itemPrize is a number input field in the form that takes it value from the JSON.
  • Each menu item (which in fact is a form) is appended to an empty div #items.
  • Once a menu item’s ‘Add to order’ button is clicked #order-form is populated by an order item. A total amount of the order is also added.

The prize in never displayed with zero decimals. I also get an error clicking submit saying ‘Enter a valid value’.

I have googled a lot about type conversion ,but all examples I have found are about converting variables. In my case the prize value is the value of a input field (which I understand always defaults to a string) I am not sure if type conversion is the problem at all really, I suspect I might be looking at the problem in the wrong way.

Please help me start untangling the decimal problem.

Lines 50 and 196 add .toFixed(2).
Lines 49, 140, 157 change number to text

EDIT:
Strangely enough it doesn’t work in Firefox :confused:
Back to drawing board.

EDIT2:
Fixed Firefox.

1 Like

Hello @jenovs

That is amazing. Thanks a lot for helping me with the decimals. I hope you can also guide me trough your reasoning and what happens in the code a bit so I’ll be wiser from this as well.

My biggest problem is how I think about type conversion. I see that you changed all input fields to text fields, and not number fields. Why is it that we are better off with text fields that displays the value as a string?

To my mind I have saved numbers just fine in the JSON but as soon as those numbers are used in input fields they are parsed to strings which means I have to make sure that they are parsed back to numbers again .It seems as I will have to argue with the code and insist that numbers are in fact numbers.