I need a function to check if a price ends with 2 digits and if it doesn't add ".00" to the end.
var price = 10;
if(!price.endsWith(2digits?)){
price.concat(price, ".00");
}
How do I achieve this?
I need a function to check if a price ends with 2 digits and if it doesn't add ".00" to the end.
var price = 10;
if(!price.endsWith(2digits?)){
price.concat(price, ".00");
}
How do I achieve this?
This will achieve what you want:
// 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");
}
This handles more cases for price and validates that it is a number.
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(null);//returns null getPrice(0);//returns "0.00" getPrice(1);//returns "1.00" getPrice(10);//returns "10.00" getPrice(10.1);//returns "10.10" getPrice(10.12);//returns "10.12" getPrice(10.123);//returns "10.12" getPrice(10.125);//returns "10.13"
it seems work this way :
var price = "23";
if (price.slice(-3).charAt(0) != '.') price = price.concat(".00");
console.log(price);