Behdad Karimi CPA
Behdad Karimi CPA

Reputation: 51

Why is Firestore storing amounts as strings instead of numbers?

I created a form which a user can fill out. One of the fields is for an amount which I specified the type to be a "number".

The form is then stored as a document in firestore which saves the amount as a string instead of a number. I have tried different methods without success.

Can anyone explain what is wrong with my code?

thanks

HTML

      <form id="create-form">

        <div class="input-field">
          <input type="number" step="0.01" id="amount" required>
          <label for="amount">Amount</label>
        </div>
.... 

JS

....
    db.collection('users').doc(user.uid).collection('items').doc('manual').collection('transactions').add({
      amount: createForm.amount.Value,
      name: createForm.name.value,
      category: createForm.category.value,
      date: createForm.date.value,
      userUID: user.uid
    })
....

Upvotes: 3

Views: 1949

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599641

When you enter data into a text input field in HTML, its value becomes a string in JavaScript code (since a text field allows input of all types of values).

If you want it to become a numeric value, you need to parse that string into a number:

parseInt(createForm.amount.Value)

Or if the user is allowed to enter non-whole numbers

parseFloat(createForm.amount.Value)

If you do that before passing the value to Firestore, it will store the numeric value instead of the string:

amount: parseFloat(createForm.amount.Value),

I had to look this up: the type="number" mostly determines what keyboard mobile users will see to enter a value, and may affect the client-side validation of the field's value. But if you access the value in JavaScript, it will still be a string, and thus require the conversion I mentioned above.

Upvotes: 4

Related Questions