Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular typescript convert string to number

I want to convert a string number (an integer represented as a string. ex "12" ) to a number

Model Class

export class Person{
  FirstName :  string | undefined ;
  Telephone:  number | undefined ;

}

TS file

  console.log("Person" + JSON.stringify(this.person));

The JSON appears as

{
    "FirstName ": "hhhhh",
    "Telephone": "1478525",
}

The Telephone property is a number and I want it to appear as follows (without the ""_ :

{
    "FirstName ": "hhhhh",
    "Telephone": 1478525,
}

Approaches I took.

this.person.Telephone = parseInt(telephone); 

Above didn't work, it shows the same number enclosed as a string. I also tried the following:

this.person.Telephone as number

both approaches didn't work. Can someone help me solve this ?

Error I get if I don't convert to a number:

"The JSON value could not be converted to System.Int32. Path: $.Telephone | LineNumber: 2 | BytePositionInLine: 18."

like image 807
Illep Avatar asked Sep 03 '25 17:09

Illep


2 Answers

I think you can try this =>

let stringToNumberData = "123";
let numberValue = Number(stringToNumberData);
console.log(numberValue);
//Returns 123

OR

if(!isNaN(Number(stringToNumberData ))){
  let numberValue = Number(stringToNumberData );
  console.log(numberValue);
} else{
    console.log('Not a Number');
}
like image 152
Srijon Chakraborty Avatar answered Sep 05 '25 06:09

Srijon Chakraborty


Just use the standard javascript Number

this.person.Telephone = Number(telephone); 
console.log("Person" + JSON.stringify(this.person));
like image 21
zerocewl Avatar answered Sep 05 '25 05:09

zerocewl