TypeScript 中的整数类型
Shuvayan Ghosh Dastidar
2023年1月30日
TypeScript
TypeScript Number
-
在 TypeScript 中使用
number类型表示数字 -
在 TypeScript 中使用
bigint表示非常大的数字 -
在 TypeScript 中使用
parseInt内置函数将字符串转换为整数 -
在 TypeScript 中使用
+运算符将字符串转换为数字
在 TypeScript 中,没有像其他编程语言那样的整数数据类型的概念。通常,只有 number 类型用于表示浮点数。
bigint 是 TypeScript 的最新版本,它表示大整数。
在 TypeScript 中使用 number 类型表示数字
TypeScript 中的 number 类型可以同时保存整数和浮点数据类型。
它还可以存储具有不同基数的数字,例如二进制、八进制和十六进制。
// the count of something is in whole numbers
var countDogs : number = 10;
// the price of a bag can be a floating point number
var priceBag : number = 200.99;
var binaryNumber : number = 0b101;
var octalNumber : number = 0o30;
var hexadecimalNumber : number = 0xFF;
console.log(countDogs);
console.log(priceBag);
console.log(binaryNumber);
console.log(octalNumber);
console.log(hexadecimalNumber);
输出:
10
200.99
5
24
255
不同基数的数字以 base 10 打印。二进制或 base 2 可以通过前缀 0b 或 0B 来表示,类似地对于 base 16,它必须以 0x 或 0X 作为前缀。
在 TypeScript 中使用 bigint 表示非常大的数字
bigint 类型用于表示非常大的数字 (numbers more than 2<sup>53</sup> - 1) 并且在整数文字的末尾有 n 字符。
var bigNumber: bigint = 82937289372323n;
console.log(bigNumber);
输出:
82937289372323
在 TypeScript 中使用 parseInt 内置函数将字符串转换为整数
parseInt 函数用于从字符串转换为整数,parseFloat 函数用于从字符串转换为浮点数据类型。
var intString : string = "34";
var floatString : string = "34.56";
console.log(parseInt(intString));
console.log(parseInt(floatString));
console.log(parseFloat(intString));
console.log(parseFloat(floatString));
var notANumber : string = "string";
console.log(parseInt(notANumber));
输出:
34
34
34
34.56
NaN
因此 parseInt 和 parseFloat 方法将返回 NaN。
在 TypeScript 中使用 + 运算符将字符串转换为数字
+ 运算符可以将字符串文字转换为 number 类型。将其转换为 number 类型后,将执行进一步的操作。
function checkiFInt( val : number | string ) {
if (( val as any) instanceof String){
val = +val as number;
}
console.log(Math.ceil(val as number) == Math.floor(val as number));
}
checkiFInt('34.5');
checkiFInt('34');
checkiFInt('34.5232');
checkiFInt('34.9');
checkiFInt('0');
输出:
false
true
false
false
true
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
