How to convert number to string inside angular 2 component:

Viewed 71075

Inside the component i have

export class AppComponent implements OnInit {


public errorMsg :number =10 ;

public doughnutChartOptions: any = {
 cutoutPercentage: 85,
  elements: {
    center: {
      text: this.errorMsg + ' Energy produced in the Energy',
      fontColor: '#fff',
      fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
      fontSize: 24,
      fontStyle: 'normal'
    }
  }
};

}

  text: this.errorMsg + ' some thing',

This is a property accepted string , so here i have to pass the number to string , How to do that in angular4,typescript 2.5

5 Answers

Integer to string is as simple as calling .toString();

As @GünterZöchbauer said TypeScript has the same type coercion as JS, so numbers are automatically converted to strings when used in a string context

So no problem will occur same as Javascript, you can use number as string.

If you want you can do it like this so :

let num = 3;//number
let stringForm = num.toString();
console.log(stringForm);

Pls try

text:  `${this.errorMsg} Energy produced in the Energy`,

NB: Use `` (back-ticks) , instead of '' (apostrophe), to get your value.

you can use ''+your number

let num:number=3;
let numTxt:string=''+number;

It will be converted into the string automatically, for an example

class myClass{
    private myNum: number = 10;
    private myName: string = "Name Surname";
    
    onInit() {
        console.log(this.myName+this.myNum);    
    }
}

will be converted into these lines when transpiled

var myClass = /** @class */ (function () {
    function myClass() {
        this.myNum = 10;
        this.myName = "Name Surname";
    }
    myClass.prototype.onInit = function () {
        console.log(this.myName + this.myNum);
    };
    return myClass;
}());

that you can check in typescript website under play ground section,

Demo

let num = 3;//number
let stringForm = num.toString();
console.log(stringForm);

Related