1

How do i fix the error odd.split is not a function at Payment.redot here is my code in typescript or ts, i am using angular.

  redot(odd){
    let o = odd.split('.');
    let decimal = '';
    if(typeof o[1] != 'undefined'){
      decimal = o[1];
      decimal = decimal.replace('%', '');
      if(decimal.length > 2){
        decimal = decimal.substr(0, 2) + '...%';
      } else {
        decimal += '%';
      }
    }
    return o[0] + '.' + decimal;
  }

4 Answers4

2

split() is the method of String, so you need to convert odd to string

  redot(odd){
    let o = odd.toString().split('.');
    ....
  }

wangdev87
  • 8,611
  • 3
  • 8
  • 31
1

Firat convert that as String

    redot(odd){
       //converAsString
        odd = odd.toString();
        let o = odd.split('.');
        let decimal = '';
        if(typeof o[1] != 'undefined'){
          decimal = o[1];
          decimal = decimal.replace('%', '');
          if(decimal.length > 2){
            decimal = decimal.substr(0, 2) + '...%';
          } else {
            decimal += '%';
          }
        }
        return o[0] + '.' + decimal;
      }
Sangar Lal
  • 50
  • 3
1

You should check if odd is a string... try declaring its type in the function parameter.

redot(odd: string) {}

This error happens when you try to use an object function that does not exists.

Check this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

I suggest to use typeof or instanceof for check if it is a string.

Check this: Check if a variable is a string in JavaScript

dmance
  • 628
  • 1
  • 8
  • 26
1

make the most of typescript. Split can be used with string only.

if you define argument type, typescript immediately tell you the error and angular code will not compile either.

enter image description here

function redot(odd: number): string {
  let o = odd ? odd.toString().split(".") : "";
  let decimal = "";
  if (o[1] != undefined) {
    decimal = o[1];
    decimal = decimal.replace("%", "");
    if (decimal.length > 2) {
      decimal = decimal.substr(0, 2) + "...%";
    } else {
      decimal += "%";
    }
    
  }
 return o[0] + (decimal ? `.${decimal}` : "");
}

console.log(redot(12));
console.log(redot(12.34));
console.log(redot(12.32334));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nilesh Patel
  • 3,193
  • 6
  • 12