Javascript 将数字字符串转换为角度 2 中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43069055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:39:33  来源:igfitidea点击:

Convert numeric string to number in angular 2

javascriptangular

提问by U rock

I want to compare angular 2 expressions. I got array of data in numeric string from my database i need to convert this to number before give a condition with ngClass for styling. how can i convert this type. any idea?

我想比较 angular 2 表达式。我从我的数据库中获得了数字字符串中的数据数组,我需要将其转换为数字,然后再使用 ngClass 给出一个条件进行样式设置。我该如何转换这种类型。任何的想法?

  <td [ngClass]= "{'positive': gbh.Last > 0, 'negative': gbh.Last < 0}"> {{gbh.Last}} </td>

回答by trees_are_great

This answer is the typescript way: so answer

这个答案是打字稿方式: 所以回答

Number('1234') // 1234
Number('9BX9') // NaN

The other answer looks like it would be for int not numbers. You are better off using the plus symbol.

另一个答案看起来像是 int 而不是数字。最好使用加号。

var x = "32";
var y = +x; // y: number

Ref answer:

参考答案

回答by Antoine Guittet

As far as I know, you can not convert your numeric string to number inside the Angular expression.

据我所知,您不能在 Angular 表达式中将数字字符串转换为数字。

The best practice will be to define a method in your controller which will solve your expression by using 'parseInt'

最佳实践是在您的控制器中定义一个方法,该方法将通过使用“ parseInt”来解决您的表达式

  function isPositive (x: String, y: number): boolean {
      return (parseInt(x, 10) < y);
  }