TypeScript – 数字

像JavaScript的TypeScript支持将数值作为Number对象。 数字对象将数字文字转换为数字类的实例。 Number类充当包装器,并允许对数字文字进行操作,因为它们是对象。

语法

var var_name = new Number(value)

如果将非数字参数作为参数传递给Number的构造函数,则它将返回NaN(Not–a–Number)

下表列出了Number对象的一组属性-

序号属性和说明
1.MAX_VALUE
JavaScript中的数字可以具有1.7976931348623157E + 308的最大可能值。
2.MIN_VALUE
JavaScript中的数字可以具有的最小可能值5E-324。
3.NaN
等于一个非数字值。
4.NEGATIVE_INFINITY
小于MIN_VALUE的值。
5.POSITIVE_INFINITY
大于MAX_VALUE的值。
6.prototype
对象的静态属性。
使用prototype属性将新属性和方法分配给当前文档中的Number对象。
7.constructor
返回创建此对象实例的函数。
默认情况下,这是Number对象。

例:

console.log("TypeScript Number Properties: "); 
console.log("Maximum value that a number variable can hold: " + Number.MAX_VALUE);
console.log("The least value that a number variable can hold: " + Number.MIN_VALUE);
console.log("Value of Negative Infinity: " + Number.NEGATIVE_INFINITY);
console.log("Value of Negative Infinity:" + Number.POSITIVE_INFINITY);

编译时,它将在JavaScript中生成相同的代码。

TypeScript Number Properties:  
Maximum value that a number variable can hold: 1.7976931348623157e+308
The least value that a number variable can hold: 5e-324
Value of Negative Infinity: -Infinity
Value of Negative Infinity:Infinity


Example: NaN

var month = 0 
if( month<=0 || month >12) { 
   month = Number.NaN 
   console.log("Month is "+ month) 
} else { 
   console.log("Value Accepted..") 
}

编译时,它将在JavaScript中生成相同的代码。

输出如下:

Month is NaN

示例:原型

function employee(id:number,name:string) { 
   this.id = id 
   this.name = name 
} 

var emp = new employee(123,"Smith") 
employee.prototype.email = "smith@abc.com" 

console.log("Employee 's Id: "+emp.id) 
console.log("Employee's name: "+emp.name) 
console.log("Employee's Email ID: "+emp.email)

编译时,它将生成以下JavaScript代码-

//Generated by typescript 1.8.10
function employee(id, name) {
   this.id = id;
   this.name = name;
}

var emp = new employee(123, "Smith");
employee.prototype.email = "smith@abc.com";

console.log("Employee 's Id: " + emp.id);
console.log("Employee's name: " + emp.name);
console.log("Employee's Email ID: " + emp.email);

其输出如下-

Employee’s Id: 123 
Emaployee’s name: Smith 
Employee’s Email ID: smith@abc.com

编号方法

Number对象仅包含作为每个对象定义一部分的默认方法。下面列出了一些常用的方法-

序号方法与说明
1.toExponential()
强制数字以指数表示法显示,即使该数字处于JavaScript通常使用标准表示法的范围内。
2.toFixed()
格式化一个数字,该数字在小数点右边具有特定的位数。
3.toLocaleString()
返回当前数字的字符串值版本,其格式可能会因浏览器的本地设置而异。
4.toPrecision()
定义要显示一个数字的总位数(包括小数点左侧和右侧的位数)。
负精度将引发错误。
5.toString()
返回数字值的字符串表示形式。
该函数将传递基数,该基数是2到36之间的一个整数,指定用于表示数值的基数。
6.valueOf()
返回数字的原始值。

觉得文章有用?

点个广告表达一下你的爱意吧 !😁