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');
}
CodePudding user response:
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: