Javascript 如何检查字符串是否以2位结尾
我需要一个函数来检查一个价格是否以两位数结尾,以及它是否没有在结尾添加“.00”Javascript 如何检查字符串是否以2位结尾,javascript,string,Javascript,String,我需要一个函数来检查一个价格是否以两位数结尾,以及它是否没有在结尾添加“.00” var price = 10; if(!price.endsWith(2digits?)){ price.concat(price, ".00"); } 如何实现这一点?这将实现您想要的: // Get the last two characters of the string var last2Chars = price.substr(price.length - 1, price.length);
var price = 10;
if(!price.endsWith(2digits?)){
price.concat(price, ".00");
}
如何实现这一点?这将实现您想要的:
// Get the last two characters of the string
var last2Chars = price.substr(price.length - 1, price.length);
// Check if the last two characters are digits
var isNumeric = /^\d+$/.test(last2Chars);
// If they are update price
if (isNumeric) {
price = last2Chars.concat(".00");
}
这将处理更多的价格案例,并验证它是否是一个数字
function getPrice(price){
var match = /^(\d*)(\.(\d+)){0,1}$/.exec(price);
if(match){
if(match[3] && match[3].length == 2){
return match[0];
}else if(!match[2]){
return price + ".00";
}else if(match[3].length == 1){
return price + "0";
}else{
return match[1] + "." + (parseInt(match[3].substr(0,2)) + (match[3].substr(2, 1) >= 5? 1: 0));
}
}
return null;
}
getPrice(空)//返回空值
getPrice(0)//返回“0.00”
getPrice(1)//返回“1.00”
getPrice(10)//返回“10.00”
getPrice(10.1)//返回“10.10”
getPrice(10.12)//返回“10.12”
getPrice(10.123)//返回“10.12”
getPrice(10.125)//返回“10.13”它似乎是这样工作的:
var price = "23";
if (price.slice(-3).charAt(0) != '.') price = price.concat(".00");
console.log(price);
.endsWith()
在这里帮不了你,因为它需要精确匹配。您可以尝试a)使用.substr()
获取最后2个字符并查看它们是否为数字,或b)使用正则表达式查看字符串是否以2位结尾。除非它是单个sigit价格,否则它将始终以两位数字结尾。我想你的意思是,你要确保(a)有一个小数点,(b)小数点后有两位数字。听起来是一个探索正则表达式的好机会,或者看看JS字符串docs.Reference for。可能的重复可能使用正则表达式模式:\d{2}$
。