简体   繁体   English

Angular typescript 将字符串转换为数字

[英]Angular typescript convert string to number

I want to convert a string number (an integer represented as a string. ex "12" ) to a number我想将一个string number (一个 integer 表示为一个字符串。例如 "12" )转换为一个number

Model Class Model Class

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

}

TS file TS文件

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

The JSON appears as JSON 显示为

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

The Telephone property is a number and I want it to appear as follows (without the ""_: Telephone 属性是一个数字,我希望它如下所示(没有“”_:

{
    "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 .上面没有用,它显示了与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." “JSON 值无法转换为 System.Int32。路径:$.Telephone | LineNumber:2 | BytePositionInLine:18。”

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');
}

Just use the standard javascript Number只需使用标准的 javascript 编号

this.person.Telephone = Number(telephone); 
console.log("Person" + JSON.stringify(this.person));

You can use unary operator +您可以使用一元运算符 +

export class Person{
  FirstName :  string | undefined;
  Telephone:  number | undefined;
}
let person = new Person();
person.FirstName = "Name";
person.Telephone = 12345;
console.log(person);
person.Telephone = +"12345";
console.log(person);

Output: Output:

Person { FirstName: 'Name', Telephone: 12345 }
Person { FirstName: 'Name', Telephone: 12345 }

PS: Use string as the data type for phone numbers. PS:使用字符串作为电话号码的数据类型。

If you want to get a number from a string, you can use this approach.如果要从字符串中获取数字,可以使用这种方法。


  
  
let person = {
name: "Some Name",
age: "45"
};

console.log('Person obj before modification ==>', person);

person.age = parseInt(person.age, 10);

console.log('Person object after modifying ==>', person);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM