I want to return the number true if it is a valid number that contains only digits with properly placed decimals and commas, otherwise return the number false. For example: if number is 1,093,222.04 or 0.232567 then my program should return the number true, but if the input were 1,093,22.04 then my program should return the number false. For example:
input: 1,093,222.04 => true
input: 0.232567 => true
input: 1267 => true
input: 1,093,22.04 => FALSE
input: 1.282,04 => FALSE
input: abcd124 => FALSE
I tried this but 1,093,222.04 returns false. It should return true
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Try using regex instead
const isNumber = x => !!`${x}`.match(/^\d*(,\d{3})*(\.\d*)?$/)
console.log(isNumber("1,093,222.04")) // true
console.log(isNumber("0.232567")) // true
console.log(isNumber("1267")) // true
console.log(isNumber("1,093,22.04")) // false
console.log(isNumber("1.282,04")) // false
console.log(isNumber("abcd124")) // false
Do note that the function must take in a string, since if you pass in the number itself, the commas , will split the "number" into different parameters
I first create a helper function to parse strings into a float. I use a regular expression to remove all characters that are not a period or digit, then I use parse float to turn it from a string into a float.
I have a function to compare test whether or not the string is properly formatted. I first convert the string to a float, then I format the float as the proper locale string. If the correctly formatted string and the string given are both the same, then I return true, otherwise I return false.
EDIT
I added some validation for long decimals, however this example is in no way meant to be a complete solution, just pointing you in the right direction. Depending on your use case you may need more validation or conditions for passing strings. i.e. this example will show .023 as invalid, because the locale string is properly 0.023. With this demo you should be able to add more validation as needed
const sToFloat = s => parseFloat(s.replace(/[^\d.]/g, ""));
function goodStringFormat(str) {
let nOfDecimals = 0;
if (str.includes(".")) nOfDecimals = str.split(".")[1].length;
const float = sToFloat(str);
const formatted = float.toLocaleString(undefined, {maximumFractionDigits: nOfDecimals});
if (formatted === str) return true;
return false;
}
console.log(`
Testing 1,093,22.04
good? ${goodStringFormat("1,093,22.04")}
Testing 0.02123123123
good? ${goodStringFormat("0.02123123123")}
Testing 1,093,222.04
good? ${goodStringFormat("1,093,222.04")}
Testing 1231231,093,222.04
good? ${goodStringFormat("1231231,093,222.04")}
`);
You can try to remove the ',' and input.replaceAll(',','') and then do the validation, but you need to have your formatter function after all the check