-5

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?

Raymond the Developer
  • 1,576
  • 5
  • 26
  • 57
  • `.endsWith()` won't help you here since it wants an *exact match*. You can try to a) use `.substr()` to get the last 2 characters and see if they are digits or b) use a regex to see if the string ends in 2 digits. – gen_Eric Jun 06 '16 at 17:42
  • 2
    Unless it's a single-sigit price it'll always end with two digits. I think what you mean is that you want to make sure that (a) there's a single decimal point, and (b) after that decimal point there are two digits. Sounds like a great opportunity to explore regex, or take a look at the JS string docs. – Dave Newton Jun 06 '16 at 17:42
  • Reference for [Using Regular Expressions on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). – Patrick Roberts Jun 06 '16 at 17:43
  • 1
    Possible duplicate of [Format number to always show 2 decimal places](http://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – Midas Jun 06 '16 at 17:45
  • 1
    Maybe use the regex pattern: `\d{2}$`. – pzp Jun 06 '16 at 17:45

3 Answers3

3

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");
}
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
1

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"

Bryan Euton
  • 919
  • 5
  • 12
0

it seems work this way :

var price = "23";
if (price.slice(-3).charAt(0) != '.')   price = price.concat(".00");
console.log(price);
kevin ternet
  • 4,514
  • 2
  • 19
  • 27