[英]Testing string for decimals for calculator
I have an array called userInput
that I am pushing my input to eventually perform an eval() calculation on. 我有一个名为
userInput
的数组,正在推送我的输入以最终对其执行eval()计算。
I am adding the decimal function but need to test if a number already has a decimal in my array to avoid something like 3.00.00.00. 我要添加小数功能,但需要测试数组中是否已经有小数以避免类似3.00.00.00之类的东西。
My current function 我目前的功能
function addPeriod() {
if((inputArray.length == 0) || inputArray[inputArray.length -1] == '.') {
//do nothing
} else {
inputArray.push('.');
console.log(inputArray);
screenText.append('.');
}
}
The way my current userInput
array looks now during operation once I use userInput.join('')
is something like 3 + 2.00 / 1
etc... I know I need to use a regex method but not sure of the pattern that would eliminate the unwanted decimal occurrence. 我现在使用
userInput.join('')
当前的userInput
数组现在在操作过程中的显示方式类似于3 + 2.00 / 1
等...我知道我需要使用正则表达式方法,但不确定要消除的模式不必要的十进制出现。 Thanks for the help. 谢谢您的帮助。
You could split the input string on a decimal and count the length. 您可以将输入字符串拆分为十进制数并计算长度。 Any input with 1 or 0 decimals should have a length of 2 or less.
任何带有小数点后缀1或0的输入的长度都应为2或更短。
var test = "3.0" // Valid, return true var test2 = ".3.0" // Invalid, return false var test3 = "30" // Valid, return true console.log(test.split('.').length <= 2) console.log(test2.split('.').length <= 2) console.log(test3.split('.').length <= 2)
Edit: While I personally prefer the readability and feel of the Regex answer, splitting is significantly faster when searching a string for existence of a certain character. 编辑:虽然我个人更喜欢Regex答案的可读性和感觉,但是在搜索字符串中是否存在某个字符时, 拆分速度明显加快 。
Here you can see a split() vs regex() speed test: 在这里,您可以看到split()与regex()速度测试:
var i = 0; var split_start = new Date().getTime(); while (i < 30000) { "1234,453,123,324".split(",").length -1; i++; } var split_end = new Date().getTime(); var split_time = split_end - split_start; i= 0; var reg_start = new Date().getTime(); while (i < 30000) { ("1234,453,123,324".match(/,/g) || []).length; i++; } var reg_end = new Date().getTime(); var reg_time = reg_end - reg_start; alert ('Split Execution time: ' + split_time + "\\n" + 'RegExp Execution time: ' + reg_time + "\\n");
This is the regex to test multiple dots: 这是测试多个点的正则表达式:
var text = "3.0.0"; var text1 = "3.0.00.00"; var text2 = "3.0"; var text3 = ".3.0"; var text4 = "30"; console.log(/^\\d+(\\.\\d{0,2})?$/.test(text)); console.log(/^\\d+(\\.\\d{0,2})?$/.test(text1)); console.log(/^\\d+(\\.\\d{0,2})?$/.test(text2)); console.log(/^\\d+(\\.\\d{0,2})?$/.test(text3)); console.log(/^\\d+(\\.\\d{0,2})?$/.test(text4));
Hope, this may help you. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.