Curtis
Curtis

Reputation: 2704

Uncaught TypeError: Object 600 has no method 'substring'

I'm simply trying to get the first and third character from a string using the following

function kFormatter(num) {
    return num > 999 ? (num/1000).toFixed(1) + 'K' : num
}
var AmountOrdered = Math.ceil($(this).val() / 100.0) * 100;
var formatAmountOrdered = kFormatter(AmountOrdered);
console.log(formatAmountOrdered.substring(0, 1));

Inside my console log I see the following error

Uncaught TypeError: Object 600 has no method 'substring' 

Upvotes: 0

Views: 1602

Answers (3)

Mike Christensen
Mike Christensen

Reputation: 91628

The issue is that if the parameter num is not greater than 999, the function will return a numeric value, not a string. Numeric values don't have a substring method.

You can modify the expression to always return a string by changing:

return num > 999 ? (num/1000).toFixed(1) + 'K' : num

to:

return num > 999 ? (num/1000).toFixed(1) + 'K' : num + ''

Upvotes: 0

antyrat
antyrat

Reputation: 27765

Seems like substring is converted to int in your code. You need to convert it to string

var formatAmountOrdered = kFormatter(AmountOrdered) + '';

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382160

Change the function to

function kFormatter(num) {
    return num > 999 ? (num/1000).toFixed(1)+'K' : ''+num
}

so that it always return a string.

Upvotes: 5

Related Questions