12

I' am currently working with the following code. In the console it's throwing

Uncaught TypeError: TotalAccountBalance.indexOf is not a function

I don't know what else to do. Searching didn't help much.

var CurrentPreservedBalance, CurrentGeneralAccountBalance, TotalAccountBalance;
    CurrentPreservedBalance = '20.56';
    CurrentGeneralAccountBalance = '20.56';
    if( CurrentPreservedBalance && CurrentGeneralAccountBalance ){
        TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance;
        console.log( TotalAccountBalance.indexOf('.') );
    } else {
        $('#total-fnpf-account-balance').val('$0.00');
        $('#total-account-balance').val('$0.00');
    }
4
  • 1
    Get rid of one of those pluses +CurrentPreservedBalance + +CurrentGeneralAccountBalance; in the middle. Then TotalAccountBalance. should work. and that plus in the front as well. Also, remove the quotes from '20.56'
    – zer00ne
    Commented Oct 2, 2016 at 20:40
  • BTW, why would you need the indexOf the decimal for?
    – zer00ne
    Commented Oct 2, 2016 at 20:46
  • @zer00ne my client has this stupid requirement which I even don't understand what's going on. Commented Oct 2, 2016 at 20:49
  • Ah, say no more, many clients indeed have moments of stupidity of great magnitudes.
    – zer00ne
    Commented Oct 2, 2016 at 20:53

3 Answers 3

33

indexOf() is a method of Strings, not Numbers.

console.log( TotalAccountBalance.toString().indexOf('.') );
1
  • 1
    Also in case if there is some null scenario for TotalAccountBalance it could be converted like this to avoid error: console.log( String(TotalAccountBalance).indexOf('.') ); Commented Aug 24, 2017 at 10:43
2
TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance;

TotalAccountBalance is the result of taking two numbers (we know they are numbers because you used the unary plus operator to convert them) and adding them together. This is another number.

indexOf is a method that you find on strings not numbers.

You could convert to a string:

(TotalAccountBalance + "").indexOf('.')
1
TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance;

The unary plus operators convert the strings into numbers; this is obviously desirable behaviour in order to get the correct mathematical result.

If you then want to use a string function (e.g. indexOf), you need to convert back to a string:

console.log( ("" + TotalAccountBalance).indexOf('.') );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.