-1

Here I create fiddle of problem. So what I am tring to do.
I use firestore for storing data and I need to store money value as number as I need to make queries like '>=' & '<=' so I can't store it as string.
What I did I check if entered number can be parsed as number and if can I parse it to number and round to two decimal places.
And it works for example for 123,457 but not for 123.456,79.
Is there better way to convert string to number so I can keep it in firestore as number?

let value = '123.456,79'; //123,457
 
function isNumeric(str) {
  if (typeof str !== 'string') {
    return false;
  }
    return (
     !isNaN(str) && 
     !isNaN(parseFloat(str))
  );
}
const valueToStore = value.replace(',', '.').replace(' ', '');

const valid = isNumeric(valueToStore);
if (valid) {
    const result = Math.round((parseFloat(valueToStore) + Number.EPSILON) * 100) / 100;

  console.log(result);
} else {
    console.log('not valid');
}
1110
  • 7,829
  • 55
  • 176
  • 334

1 Answers1

1

For monetary values it's most common to store them as discrete numbers in the smallest fraction that the currency supports. So for most currencies that means that you store the value as cents, and not as whole units.

In our code that means I'd remove the / 100 from the calculation, which would then end up storing a value of 12345679.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Sorry I already feel stupid on this topic but is your suggestion to make calculation to get integer at all or just strip dots and commas from provided number in db? – 1110 Jul 26 '22 at 16:40
  • The former: store the currency as whole values only, without any fractions (the links explain better why that is). – Frank van Puffelen Jul 26 '22 at 16:51