简体   繁体   English

Javascript验证数字逗号和小数

[英]Javascript validate number commas and decimal

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.例如:如果数字是 1,093,222.04 或 0.232567 那么我的程序应该返回数字真,但如果输入是 1,093,22.04 那么我的程序应该返回数字假。 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.我试过了,但 1,093,222.04 返回 false。 It should return true它应该返回真

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

Something like this might help you solve your issue.像这样的事情可能会帮助您解决问题。

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.如果格式正确的字符串和给定的字符串都相同,则返回true,否则返回false。

This may produce unexpected results when there are strings given that have more than one period.当给定的字符串包含多个句点时,这可能会产生意外的结果。

hopefuly this points you in the right direction, happy coding!🚀希望这为您指明了正确的方向,快乐编码!🚀

 const sToFloat = s => parseFloat(s.replace(/[^\\d.]/g, "")); function goodStringFormat(str) { const float = sToFloat(str); const formatted = float.toLocaleString(); if (formatted === str) return true; return false; } console.log(` Testing 1,093,22.04 good? ${goodStringFormat("1,093,22.04")} Testing 1,093,222.04 good? ${goodStringFormat("1,093,222.04")} `);

您可以尝试删除 ',' 和input.replaceAll(',','')然后进行验证,但您需要在所有检查后都有格式化程序功能

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确实注意到,该功能必须在一个字符串,因为如果你在数通本身,逗号,将分裂的“数量”为不同的参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM